简体   繁体   English

使来自C#空类实例的序列化JSON返回空数组

[英]Make serialized JSON from C# null class instance return empty array

Given the following simple class: 给定以下简单的类:

public class Person
{
  public int id { get; set; }
  public List<Order> orders { get; set; }
}

When the orders property is null, and once the Person instance is serialized using JSON.NET below: orders属性为null,并且使用以下JSON.NETPerson实例进行序列化后:

var json = JsonConvert.SerializeObject(myPerson);

I need the physical output returned (it's an existing constraint) to look like the following when orders = null : orders = null时,我需要返回的物理输出(这是一个现有约束),如下所示:

{
 "id": 1,
 "orders": []
}

However, what is happening is that the orders property is being returned with all null values like below: 但是,正在发生的情况是orders属性返回的所有空值如下所示:

{
 "id": 1,
 "orders": [
    {
      "id": null,
      "total":null,
      "orderDate":null,
      "itemQuantity":null
    }
  ]
}

I can't have that collection be returned if null but rather it needs to show as basically an empty array like: "orders": []" 如果为null ,则无法返回该集合,而是需要将其显示为基本上为空的数组,例如: "orders": []"

I've tried: 我试过了:

myPerson.orders = null;

However, this still produces the full object collection being displayed with all null values. 但是,这仍然会产生完整的对象集合,并显示所有空值。

How can I intervene on the serialization or manipulation of this object so I can have it physically return as an empty array as opposed to an expanded null collection of fields? 我该如何干预此对象的序列化或操作,以使它以物理形式返回为空数组,而不是扩展的null字段集合?

EDIT: A portion of the question was answered via the comments. 编辑:部分问题通过评论得到了回答。 The full blown object instance being returned was due to a LINQ query returning a resultset that instantiated a default instance OF orders . 返回的完整对象实例是由于LINQ查询返回了实例化默认orders实例的结果集。 However the main part of the question is still about making it return "orders":[] and not "orders":null 但是,问题的主要部分仍然是使它返回"orders":[]不是 "orders":null

"orders": [
  {
    "id": null,
    "total":null,
    "orderDate":null,
    "itemQuantity":null
  }
]

The output you see above cannot be caused by an empty orders property of the person. 您在上面看到的输出不能由人员的空orders属性引起。 The JSON array does have an item, so there needs to be an item in the orders list too. JSON数组确实有一个项目,因此订单列表中也需要有一个项目。 It just happens to have the default value for all its properties which is why there is a null for every key. 它恰好具有其所有属性的默认值,这就是为什么每个键都为null原因。

So if you figure out where that empty Order object is being created and added to the list, you can get rid of that output. 因此,如果您确定在哪里创建了空的Order对象并将其添加到列表中,则可以摆脱该输出。

As for serializing an empty list, you have two options: You can either serialize it as null by setting the property to null directly ( person.orders = null ). 至于序列化一个空列表,你有两个选择:你可以把它序列化的null通过设置属性为null直接( person.orders = null )。 Or you can serialize it as an empty array [] by assigning an empty list ( person.orders = new List<Order>() ) to the property. 或者,您可以通过为属性分配一个空列表( person.orders = new List<Order>() )将其序列化为一个空数组[]

You can also manipulate the serializer to always create an empty array even if the property is null . 您也可以操纵序列化程序以始终创建一个空数组,即使该属性为null See this answer for an example. 有关示例,请参见此答案

You can initialize the collection in the class constructor, and then you will get your desired output: 您可以在类构造函数中初始化集合,然后将获得所需的输出:

public class Person
{
    public Person()
    {
        orders = new List<Order>();
    }

    public int id { get; set; }
    public List<Order> orders { get; set; }
}

Also, you can personalize the getter for your property, but personally I don't recommend it because it can be hard to find in case of errors. 另外,您可以为您的财产个性化吸气剂,但我个人不建议这样做,因为在出​​现错误的情况下很难找到它。

public class Person
{       
    public int id { get; set; }

    private List<Order> _orders;

    public List<Order> orders
    {
        get
        {
            if (_orders == null)
            {
                _orders = new List<Order>();
            }

            return _orders;
        }
        set { _orders = value; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM