我正在调用一个返回jso序列化对象列表的servie,如下所示:
{ “雇员”:[{ “雇员”:{ “ID”: “1”, “DATE_CREATED”: “2011-06-16T15:03:27Z”, “扩展”:[{ “地址”:{ “street1”:“12345 first st。”,“city”:“Denver”,“state”:“CO”}}]}},{“employee”:{“id”:“2”...
因此,您可以看到我首先拥有一个名为employees的员工对象列表。最重要的是,每个雇员对象包含另一个名为extended的对象,用于扩展信息(在本例中为地址信息)。我想要实现的是将整个列表作为字符串传递给反序列化器并使用Employee对象返回List,如下所示:
[Serializable]
public class Employee {
public string Id { get; set; }
public string DateCreated { get; set; }
public ExtendedProperties Address { get; set; }
}
[Serializable]
public class ExtendedProperties
{
public string Street1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
我找到了使用NEwtonSoft的类似例子,但就复合对象而言,它们并不完全相同。如果需要,我可以删除扩展属性。但这远非理想。
非常感谢任何帮助。
TIA!
答案 0 :(得分:4)
嗯,这里有一些事情:
employees
属性映射到实际的属性集合。您可以使用单独的类处理它,也可以使用LINQ to JSON读取整个内容,然后在反序列化集合之前挖掘一层。date_created
转换为DateCreated
,尽管我敢说它可以。我已经把一些事情搞砸了 - 但这有点难看:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
public class EmployeeCollection {
public List<EmployeeWrapper> Employees { get; set; }
}
public class EmployeeWrapper {
public Employee Employee { get; set; }
}
public class Employee {
public string Id { get; set; }
public string Date_Created { get; set; }
public List<ExtendedProperty> Extended { get; set; }
}
public class ExtendedProperty {
public Address Address { get; set; }
}
public class Address
{
public string Street1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
class Test
{
static void Main()
{
string json = @"{""employees"":
[{""employee"":
{""id"":""1"",
""date_created"":""2011-06-16T15:03:27Z"",
""extended"":[
{""address"":
{""street1"":""12345 first st."",
""city"":""Denver"",
""state"":""CO""}}]
}}]}";
var employees =
JsonConvert.DeserializeObject<EmployeeCollection>(json);
foreach (var employeeWrapper in employees.Employees)
{
Employee employee = employeeWrapper.Employee;
Console.WriteLine("ID: {0}", employee.Id);
Console.WriteLine("Date created: {0}", employee.Date_Created);
foreach (var prop in employee.Extended)
{
Console.WriteLine("Extended property:");
Address addr = prop.Address;
Console.WriteLine("{0} / {1} / {2}", addr.Street1,
addr.City, addr.State);
}
}
}
}
如果您想保留原始类结构,我建议您使用LINQ to JSON进行更多手动转换。当你习惯了JSON库时,这并不是特别困难 - 特别是如果你对LINQ to Objects感到满意。