json.net list serialization to JSON Array

30,175

If you want your inputs to be an array, you need to declare it as an array in your object :

class PeopleList {
    public List<Person> inputs { get; set; }
}

Then you can use it :

var json = new List<PeopleList>();
List<Person> p1 = new List<Person> { new Person { name = "Name 1", age = 20 } };
json.Add(new PeopleList { inputs = p1 });
List<Person> p2 = new List<Person> { new Person { name = "Name 2", age = 30 } };
json.Add(new PeopleList { inputs = p2 });

string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
Share:
30,175
thunder
Author by

thunder

Updated on April 28, 2020

Comments

  • thunder
    thunder almost 4 years

    I'm using json.net to serialize an object to a json string. Now I have a list of Objects which I like to serialize into a Json array. However, I'm unable to do that with json.net and hope someone can point out my mistake.

    I have the following classes:

    class PeopleList {
        public Person inputs { get; set; }
    }
    
    class Person {
        public String name { get; set; }
        public int age { get; set; }
    }
    

    I'm using the following code to serialize the objects:

    var json = new List<PeopleList>();
    Person p1 = new Person { name = "Name 1", age = 20 };
    json.Add(new PeopleList { inputs = p1 });
    Person p2 = new Person { name = "Name 2", age = 30 };
    json.Add(new PeopleList { inputs = p2 });
    
    
            string jsonString = JsonConvert.SerializeObject(json, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
    

    This gives me the following output:

    [
      {
        "inputs": {
          "name": "Name 1",
          "age": 20
        }
      },
      {
        "inputs": {
          "name": "Name 2",
          "age": 30
        }
      }
    ]
    

    Here is what I actually want:

    [
      {
        "inputs": [
          {
            "name": "Name 1",
            "age": 20
          }
        ]
      },
      {
        "inputs": [
          {
            "name": "Name 2",
            "age": 30
          }
        ]
      }
    ]
    

    As you see I need every object in my list encapsulated with []. How can I achieve that with Json.net? Thanks!