对象列表到Json字符串

时间:2014-11-06 04:41:58

标签: c# asp.net asp.net-mvc asp.net-mvc-5

如何将对象列表转换为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);

}

3 个答案:

答案 0 :(得分: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 :(得分:0)

return Json()

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

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

return Json(new {People=PersonList});

答案 2 :(得分: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);

}

这将完全返回你想要的