2017-05-27 14 views
0

我有一個像示例波紋管的JSON,我使用C#和json.net。 我試圖將這個json反序列化成一個對象,但它不工作。C#,Deserialize json

{ 
    "classes": [{ 
     "id": 1, 
     "mask": 1, 
     "powerType": "rage", 
     "name": "Warrior" 
    }, { 
     "id": 2, 
     "mask": 2, 
     "powerType": "mana", 
     "name": "Paladin" 
    }, { 
     "id": 3, 
     "mask": 4, 
     "powerType": "focus", 
     "name": "Hunter" 
    }, { 
     "id": 4, 
     "mask": 8, 
     "powerType": "energy", 
     "name": "Rogue" 
    }, { 
     "id": 6, 
     "mask": 32, 
     "powerType": "runic-power", 
     "name": "Death Knight" 
    }, { 
     "id": 12, 
     "mask": 2048, 
     "powerType": "fury", 
     "name": "Demon Hunter" 
    }] 
} 

1)我創建了一個類:

public class ClassJson 
{ 
    [JsonProperty(PropertyName = "classes")] 
    public Class Class { get; set; } 
} 

2)第二類:

public class Class 
{ 
    [JsonProperty(PropertyName = "id", NullValueHandling = NullValueHandling.Ignore)] 
    public int Id { get; set; } 

    [JsonProperty(PropertyName = "powerType", NullValueHandling = NullValueHandling.Ignore)] 
    public string PowerType { get; set; } 

    [JsonProperty(PropertyName = "name", NullValueHandling = NullValueHandling.Ignore)] 
    public string Name { get; set; } 
} 

我調用API,得到JSON和我簡單地調用JsonConvert.DeserializeObject<List<ClassJson>>(json)。沒有任何反應,沒有錯誤。

有人可以給我一個提示,以便更好地構建類嗎?

public class ClassJson 
{ 
    [JsonProperty(PropertyName = "classes")] 
    public Class[] classes { get; set; } 
} 

你並不需要編寫的類手動表示JSON:

+2

給定json中的'classes'表示一個數組。所以你需要聲明屬性爲'public Class [] Classes {get;組; }'。這應該工作。 –

+0

嘗試JsonConvert.DeserializeObject (json)。類是一個集合屬性。 –

+2

我認爲'類'應該是一個'列表',或其他集合類型。因爲它是json中的一個數組。 –

回答

1

因爲classes應該是一個數組,而不是嘗試。請參考我的回答here瞭解如何創建JSON的類表示。

+0

感謝這個提示,我不知道這個快捷方式創建類給定一個JSON! – Maturano