简体   繁体   中英

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:

var json = JsonConvert.SerializeObject(myPerson);

I need the physical output returned (it's an existing constraint) to look like the following when orders = null :

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

However, what is happening is that the orders property is being returned with all null values like below:

{
 "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": []"

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?

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 . However the main part of the question is still about making it return "orders":[] and not "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. The JSON array does have an item, so there needs to be an item in the orders list too. It just happens to have the default value for all its properties which is why there is a null for every key.

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.

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 ). Or you can serialize it as an empty array [] by assigning an empty list ( person.orders = new List<Order>() ) to the property.

You can also manipulate the serializer to always create an empty array even if the property is 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; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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