我正在使用 json.net 将对象序列化为json字符串。现在我有一个对象列表,我喜欢将其序列化为 Json 数组。但是,我无法用 json.net 做到这一点,并希望有人可以指出我的错误。
我有以下课程:
class PeopleList {
public Person inputs { get; set; }
}
class Person {
public String name { get; set; }
public int age { get; set; }
}
我使用以下代码来序列化对象:
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 });
这给了我以下输出:
[
{
"inputs": {
"name": "Name 1",
"age": 20
}
},
{
"inputs": {
"name": "Name 2",
"age": 30
}
}
]
这是我真正想要的:
[
{
"inputs": [
{
"name": "Name 1",
"age": 20
}
]
},
{
"inputs": [
{
"name": "Name 2",
"age": 30
}
]
}
]
如您所见,我需要用 [] 封装列表中的每个对象。我怎样才能通过 Json.net 实现这一目标?谢谢!
如果您希望输入是数组,则需要在对象中将其声明为数组:
class PeopleList {
public List<Person> inputs { get; set; }
}
然后你可以使用它:
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 });
根据您的输出和您想要的内容,您可能想做这样的事情
Json2CSharpClass Converter
public class Person
{
public string name { get; set; }
public int age { get; set; }
}
public class PeopleList
{
public List<Person> inputs { get; set; }
}