我有以下类
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转换为测试对象,下面的代码正确转换为"名称",但"字段"总是返回null。
Test returnTest = JObject.Parse(json).ToObject<Test>()
关于如何使"字段"返回数组的任何想法?
以下作品DotNetFiddle示例:
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; }
}