List of Objects To Json String

不打扰是莪最后的温柔 提交于 2019-12-08 10:44:18

问题


How do you turn a list of Objects into a JSON String?

The code below returns only one attribute, People. How to add multiple attributes to it? I have been using JsonConvert to change an object into JSON format. I would be open other options / opinions on how to do it. Any help would be much appriciated!

Wanted Response:

{"People":
    {"Person": 
        {"FirstName":"Mike", "LastName":"Smith", "Age":"26"}
    },
    {"Person": 
        {"FirstName":"Josh", "LastName":"Doe", "Age":"46"}
    },
    {"Person": 
        {"FirstName":"Adam", "LastName":"Fields", "Age":"36"}
    }
} 

The Person Class

public class Person
{
    public string FirstName { get ;set; }
    public string LastName { get ;set; }
    public int Age { get ;set; }    
}

Processing Logic

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

}

回答1:


Create a list of objects.

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

will return

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



回答2:


The

return Json()

will actually serialize the object it takes as a parameter. As you are passing in a json string, it's getting double encoded. Create an anonymous object with a property named People, then serialize it. so you can:

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

or

return Json(new {People=PersonList});



回答3:


you need add a class, we will name it 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);

}

this shall return exactly what you want



来源:https://stackoverflow.com/questions/26771869/list-of-objects-to-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!