7

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!

1
  • Make inputs into a list or an array if you want it to be an array in JSON also Commented Apr 26, 2016 at 15:02

2 Answers 2

14

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 });
3
  • Great! Works perfect! I somehow just didn't find the solution after trying for a long time. But now it's obvious. Thanks!
    – thunder
    Commented Apr 27, 2016 at 15:48
  • Why are you using a List? Can the library not handle arrays? Commented Jul 10, 2019 at 10:15
  • You can use arrays. I think I used List because the word was in the OP question.
    – PMerlet
    Commented Jul 10, 2019 at 14:41
-3

based on your output and what you want you probably want to do something like this

Json2CSharpClass Converter

public class Person
{
    public string name { get; set; }
    public int age { get; set; }
}

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.