我有一个对象Person
这样的:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
我尝试创建这样的列表:
var personList = new List<object>();
personList.Add(new Person { Address = "addr1", Age = 20, Name = "Person1" });
personList.Add(new Person { Address = "addr2", Age = 22, Name = "Person2" });
personList.Add(new Person { Address = "addr3", Age = 25, Name = "Person1" });
var jsonString = JsonConvert.SerializeObject(personList);
这是jsonString
的结果
[{"Name":"Person1","Age":20,"Address":"addr1"},
{"Name":"Person2","Age":22,"Address":"addr2"},
{"Name":"Person1","Age":25,"Address":"addr3"}]
以下是我的预期结果,那么我该怎么做呢?
{
Person1:{"Name":"Person1","Age":20,"Address":"addr1"},
Person2:{"Name":"Person2","Age":22,"Address":"addr2"},
Person3:{"Name":"Person3","Age":25,"Address":"addr3"}
}
当我没有错的时候,你必须使用Dictionary<string, Person>
。这应该以这种方式序列化它,你想要它。
如果不需要冗余数据,可以选择将属性[JsonIgnore]
添加到Name
。
编辑:您可以使用自定义 JsonConverter:Newtonsoft.Json 将集合序列化(使用索引器)作为字典直接序列化到字典
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
// constructor
public Person(string name, int age, string address){
this.Name = name;
this.Age = age;
this.Address = address;
}
}
然后
List<person>People = new List<person>();
People.Add(new Person("name1", 1, "address1"));
People.Add(new Person("name2", 2, "address2"));
People.Add(new Person("name3", 3, "address3"));
string jsonString = JsonConvert.SerializeObject(People);
然后在客户端上,省略有关将其提供给客户端的部分
var people = JSON.parse(jsonString)