2014-11-06 55 views
0

如何将对象列表转换为JSON字符串?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"} 
    } 
} 

Person类

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

} 
+0

确切你发布的字符串是“你想要的输出”是无效的JSON。它有一个属性标识符,后面跟着三个裸露的对象。 – user12864 2014-11-06 05:03:17

+0

检查此,它可能为你工作太: http://stackoverflow.com/questions/26547890/system-collections-generic-list-from-cs-to-js-variable/26549074#26549074 – 2014-11-06 05:27:03

+0

一更好的方法是使用WebAPI,然后根据请求简单地返回'List '和框架句柄将其转换为Json(或Xml)。 – 2014-11-06 05:57:33

回答

3

创建一个对象列表。

List<Person> persons = new List<Person>(); 
persons.Add(new Person { FirstName = "John", LastName = "Doe" }); 
// etc 
return Json(persons, JsonRequestBehavior.AllowGet); 

将返回

[{"FirstName":"John", "LastName":"Doe"}, {....}, {....}] 
+1

这不会创建具有People数组的对象,这是所需的结果。在序列化之前将其放入一个匿名对象中。 – iceburg 2014-11-06 05:17:11

+0

@iceburg,不确定OP需要什么。标题说__对象_和_Wanted Response_列表无效 – 2014-11-06 05:47:53

+0

@iceburg你是对的,但这工作正常。它只会使用索引而不是“人物”数组属性。 – MGot90 2014-11-06 15:39:07

0

return Json() 

实际上将其序列作为参数的对象。当你传递一个json字符串时,它会被双重编码。 使用名为People的属性创建一个匿名对象,然后对其进行序列化。 所以你可以:

return Content(JsonConvert.SerializeObject(new {People=PersonList})) 

return Json(new {People=PersonList}); 
0

你需要添加一个类,我们将它命名为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); 

} 

本应返回正是你想要的