在C#中将json对象列表反序列化为POCO对象

本文关键字:对象 反序列化 POCO 列表 中将 json | 更新日期: 2023-09-27 17:59:20

我正在调用一个服务,该服务返回jso序列化对象的列表,例如:

{"employees":[{"employee":{"id":"1","date_created":"2011-06-16T15:03:27Z","extended":[{"address":{"street1":"12345 first st.","city":"Denver","state":"CO"}}]}}

所以,你可以看到,我首先有一个名为employees的employee对象列表。除此之外,每个employee对象都包含另一个名为extended for extended info(在本例中为地址信息)的对象。我想实现的是将整个列表作为字符串传递给反序列化程序,并返回一个列表,其中Employee对象如下所示:

[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!

在C#中将json对象列表反序列化为POCO对象

这里有一些东西:

  • 您有一两个外部"包装器"级别,将employees属性映射到实际的属性集合。您可以用一个单独的类来处理它,也可以使用LINQ to JSON读取整个内容,然后在反序列化集合之前挖掘一层
  • 看起来实际上每个员工都有一个扩展属性的集合,扩展属性中的一个属性是地址
  • 我不知道如何说服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到JSON进行更手动的转换。当你习惯了JSON库时,这并不难,尤其是如果你对LINQ to Objects很满意的话。