我有以下课程
public class Test
{
public string name;
public List<Field> fields;
}
public class Field
{
public string id;
public string name;
}
以及以下Json
{
"name": "name1",
"fields": [
{
"id": "4786182461",
"name": "field1",
},
{
"id": "41241241122",
"name": "field2",
},
]
}
我试图将此json转换为Test对象,以下代码正确转换了&#34; name&#34;,但&#34;字段&#34;总是返回null。
Test returnTest = JObject.Parse(json).ToObject<Test>()
关于如何制作&#34;字段&#34;的任何想法返回数组?
答案 0 :(得分:0)
以下作品DotNetFiddle Example:
public static void Main()
{
var json = "{\"name\": \"name1\",\"fields\": [{\"id\": \"4786182461\",\"name\": \"field1\",},{\"id\": \"41241241122\",\"name\": \"field2\",}, ]}";
var result = JsonConvert.DeserializeObject<Test>(json);
Console.WriteLine(result.Name);
Console.WriteLine(result.Count);
}
public class Test
{
public string Name;
public List<Field> Fields;
}
public class Field
{
public string id;
public string name;
}
结果:
NAME1
2
但是,我强烈建议您坚持使用最佳做法并使用属性,例如:
public class Test
{
public string Name { get; set; }
public List<Field> Fields { get; set; }
}