Json字符串的对象列表
本文关键字:列表 对象 字符串 Json | 更新日期: 2023-09-27 18:29:23
如何将对象列表转换为JSON字符串
下面的代码只返回一个属性People。如何为其添加多个属性?我一直在使用JsonConvert将一个对象更改为JSON格式。关于如何做,我愿意提供其他选择/意见。任何帮助都将不胜感激!
通缉回应:
{"People":
{"Person":
{"FirstName":"Mike", "LastName":"Smith", "Age":"26"}
},
{"Person":
{"FirstName":"Josh", "LastName":"Doe", "Age":"46"}
},
{"Person":
{"FirstName":"Adam", "LastName":"Fields", "Age":"36"}
}
}
人员类别
public class Person
{
public string FirstName { get ;set; }
public string LastName { get ;set; }
public int Age { get ;set; }
}
处理逻辑
public JsonResult GetAllPeople()
{
List<Person> PersonList = new List<Person>();
String responseJSON = "";
foreach(string data in something){
//Some code to get data
Person p = new Person();
p.FirstName = data.FirstName ;
p.LastName = data.LastName
p.Age = data.Age;
responseJSON += new { Person = JsonConvert.SerializeObject(p) };
}
return Json(new { People = JsonConvert.SerializeObject(responseJSON ) }, JsonRequestBehavior.AllowGet);
}
创建一个对象列表。
List<Person> persons = new List<Person>();
persons.Add(new Person { FirstName = "John", LastName = "Doe" });
// etc
return Json(persons, JsonRequestBehavior.AllowGet);
将返回
[{"FirstName":"John", "LastName":"Doe"}, {....}, {....}]
return Json()
将实际序列化它作为参数的对象。当您传入一个json字符串时,它会被双重编码。创建一个具有名为People的属性的匿名对象,然后对其进行序列化。所以你可以:
return Content(JsonConvert.SerializeObject(new {People=PersonList}))
或
return Json(new {People=PersonList});
您需要添加一个类,我们将其命名为People
public class People{
public Person Person{set;get;}
}
public JsonResult GetAllPeople()
{
List<People> PeopleList= new List<People>();
foreach(string data in something){
//Some code to get data
Person p = new Person();
p.FirstName = data.FirstName ;
p.LastName = data.LastName
p.Age = data.Age;
PeopleList.Add(new People(){Person = p});
}
return Json(new { People = PeopleList },JsonRequestBehavior.AllowGet);
}
这将返回您想要的