List of Objects To Json String

2019-06-14 11:03发布

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

}

3条回答
做个烂人
2楼-- · 2019-06-14 11:15

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"}, {....}, {....}]
查看更多
三岁会撩人
3楼-- · 2019-06-14 11:27

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

查看更多
劳资没心,怎么记你
4楼-- · 2019-06-14 11:39

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});
查看更多
登录 后发表回答