我有一个像这样的对象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"}
}
答案 0 :(得分:1)
当我没错的时候你必须使用 {{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
。
这应该按照这种方式序列化,你想要它。
如果您不想要冗余数据,可以选择将Dictionary<string, Person>
添加到[JsonIgnore]
。
修改:您可以使用自定义JsonConverter将列表直接序列化到字典:Newtonsoft.Json serialize collection (with indexer) as dictionary
答案 1 :(得分:-1)
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)