简体   繁体   中英

json.net list serialization to JSON Array

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!

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 });

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; }
}

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