我有困難時與此JSON:無法生成正確的類
{
"tester": [
{
"type": {
"ID": "R89d",
"Description": "Test",
"lastUpdated": "2016-03-20 20:45:09",
},
"specification": {}
},
{
"type": {
"ID": "RB01",
"Description": "Another test",
"lastUpdated": null
},
"specification": {
"0": {
"ID": "RB01",
"number": 1,
"Type": "RB"
},
"1": {
"ID": "RB01",
"number": 3,
"Type": "RB"
}
}
},
{
"type": {
"ID": "RT40",
"Description": "Test 2",
"lastUpdated": null,
},
"specification": {}
}
]
}
特別
當我把它變成json2c#網站我得到這個類:
public class Type
{
public string ID { get; set; }
public string Description { get; set; }
public string lastUpdated { get; set; }
}
public class __invalid_type__0
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
public class __invalid_type__1
{
public string ID { get; set; }
public int number { get; set; }
public string Type { get; set; }
}
public class Specification
{
public __invalid_type__0 __invalid_name__0 { get; set; }
public __invalid_type__1 __invalid_name__1 { get; set; }
}
public class Tester
{
public Type type { get; set; }
public Specification specification { get; set; }
}
public class RootObject
{
public List<Tester> tester { get; set; }
}
我不不知道爲什麼該網站返回我invalid type
因爲JSON語法是正確的。我的目標是創建一個類,允許我讀取specification
的所有屬性,如何在json中看到有一個對象數組。我需要做的是創建一些東西,使我可以訪問所有specification
對象值,如ID - Number - Type
。其實我只用像這樣類型管理它:
string responseText = "json above";
var obj = JsonConvert.DeserializeObject<RootObject>(responseText);
foreach(var item in obj.Tester){ //loop through Tester item
//what I need:
foreach(var spec in item.specification){ //not possible
spec.Description; ...
}
}
雖然JSON語法是正確的,但這並不意味着它可以爲它創建一個有效的C#類型。您發佈的JSON會導致「0」和「1」屬性名稱無效。是否有機會將您的JSON輸出複製到_actual_數組,而不是具有類數組屬性的對象?雖然您可以花時間以某種方式對此進行反序列化,但更快更清潔的方法很可能會修復源代碼。 –
考慮到當前生成的Type類,'type'似乎也有問題。 –
@JamesThorpe我只能刪除'「0」和「」1「'我不知道這個編輯是否有幫助。這:http://pastebin.com/LXPzrmjJ – Dillinger