Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize object of multiple classes into a single JSON using Json.NET

I want to join objects of several classes together into a single JSON response, using Json.NET. I want to build the following into a single JSON response:

{
  "data": [
    {
      "from": {
        "name": "Pawan Shrestha",
        "id": "100001187416487"
      },
      "created_time": "2012-04-22T10:21:22+0000",
      "unread": true,
      "to": {
        "name": "Shashwat Tripathi",
        "id": "100000559654730"
      }
    }
  ],
  "summary": {
    "unread_count": 1,
    "total_count": 1,
    "updated_time": "2012-04-22T10:21:22+0000"
  }
  "response_generated_on" : "2012-04-12 14:23:33"
}

I am creating JSON responses in the following way:

Customer cs = new Customer(2011); //2011 is Customer A/c No.
string j = JsonConvert.SerializeObject(cs);
like image 242
shashwat Avatar asked Apr 22 '12 13:04

shashwat


People also ask

Can JSON serialize a list?

Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.

What is serializing in JSON?

Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.

How do you deserialize an object in C#?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

Is polymorphic deserialization possible in System text JSON?

There is no polymorphic deserialization (equivalent to Newtonsoft. Json's TypeNameHandling ) support built-in to System. Text. Json .


1 Answers

You can use anonymous types:

JsonConvert.SerializeObject(new {
    data = new[] { ... },
    summary = ...
});
like image 70
SLaks Avatar answered Nov 03 '22 23:11

SLaks