Json字符串的对象列表 [英] List of Objects To Json String

查看:232
本文介绍了Json字符串的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象列表转换为JSON字符串?

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

下面的代码仅返回一个属性People.如何为其添加多个属性?我一直在使用JsonConvert将对象更改为JSON格式.我会就如何做到这一点开放其他选择/意见.任何帮助将不胜感激!

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!

想要的答复:

{"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"}, {....}, {....}]

这篇关于Json字符串的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆