我想显示SyncEntity的列表,其中包含我的类中的另一个EntityField列表,但我只得到“JSONReader.SyncEntity”作为输出, 如何将输出作为SyncEntity列表。下面是我的代码片段。
namespace JSONReader
{
public class SyncEntity
{
public string Name { get; set; }
public string Id { get; set; }
public string Modified { get; set; }
public List<EntityField> EntityFields { get; set; }
}
public class EntityField
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
public class RootObject
{
public List<SyncEntity> SyncEntity { get; set; }
}
}
以下是我的主要课程:
class Program
{
static void Main()
{
ExecuteEmployeeSearch();
Console.ReadLine();
}
static void ExecuteEmployeeSearch()
{
List<SyncEntity> datalist = JsonConvert.DeserializeObject<List<SyncEntity>>(File.ReadAllText(@"E:\\JsonDemo.json"));
datalist.ForEach(Console.WriteLine);
}
}
以下是我的JSON格式:
[{
"SyncEntity": [{
"Name": "Vivek",
"Id": "24",
"Modified": "30-Dec-2017",
"EntityFields": [{
"Name": "Absolute No",
"Type": "String",
"Value": "string"
},
{
"Name": "Description",
"Type": "String",
"Value": "String"
}
]
}]
}]
我错过了在实体字段列表中获取SyncEntity列表,谢谢高级
答案 0 :(得分:0)
您的JSON结构表明您需要在反序列化时请求RootObject
的列表。试试这个
var data = JsonConvert.DeserializeObject<List<RootObject>>(File.ReadAllText(@"E:\\JsonDemo.json"));
data.ForEach(Console.WriteLine);
我猜你还需要将SyncEntity
定义为一个对象,而不是JSON
文件中的数组。如果它看起来像这样
[{
"Name": "Vivek",
"Id": "24",
"Modified": "30-Dec-2017",
"EntityFields": [{
"Name": "Absolute No",
"Type": "String",
"Value": "string"
},
{
"Name": "Description",
"Type": "String",
"Value": "String"
}
]
}]
在上述情况下,您的新模型类应具有以下结构
public class EntityField
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
public class SyncEntity
{
public string Name { get; set; }
public string Id { get; set; }
public string Modified { get; set; }
public List<EntityField> EntityFields { get; set; }
}
在此之后,您现在可以反序列化为List<SyncEntity>
。为了显示您的数据,您应该遍历此列表并打印相关属性
var data = JsonConvert.DeserializeObject<List<SyncEntity>>(File.ReadAllText(@"E:\\JsonDemo.json"));
data.ForEach(se =>
{
Console.WriteLine("The sync entity name is " + se.Name + ". And it has the following fields:");
se.EntityFields.ForEach(ef =>
{
Console.WriteLine("{0} of type {1} with value {2}", ef.Name, ef.Type, ef.Value);
});
});
我希望这会有所帮助。