想要更改JSON格式

时间:2015-05-13 03:56:33

标签: c# asp.net json

我有这个班级

public class Contact {
     #regionContact Info
     public Guid ContactID { get; set; }
     public string Name { get; set; }
     public string RegID { get; set; }
     public string MobileNumber { get; set; }
     public string Tel { get; set; }
     #endregion 
}

当我调用getAllContact()方法时,我得到了这个结果

[{"ContactID":"7abe6291-43f2-e411-b150-000c2975315f","Name":"Visitor 1","RegID":"1","MobileNumber":"1122334455","Tel":"1122334455"},{"ContactID":"f76f310f-a3f3-e411-b150-000c2975315f","Name":"Visitor 2","RegID":"2","MobileNumber":null,"Tel":null},{"ContactID":"9b3e6018-a3f3-e411-b150-000c2975315f","Name":"Visitor 3","RegID":"3","MobileNumber":null,"Tel":null}]

但我想要的是这种格式。

{"contacts":[{"ContactID":"7abe6291-43f2-e411-b150-000c2975315f","Name":"Visitor 1","RegID":"1","MobileNumber":"1122334455","Tel":"1122334455"},{"ContactID":"f76f310f-a3f3-e411-b150-000c2975315f","Name":"Visitor 2","RegID":"2","MobileNumber":null,"Tel":null},{"ContactID":"9b3e6018-a3f3-e411-b150-000c2975315f","Name":"Visitor 3","RegID":"3","MobileNumber":null,"Tel":null}]}

如何更改以获取此json格式?请问有人帮帮我吗?

3 个答案:

答案 0 :(得分:0)

你的getAllContact()方法应该是一个对象,其中有一个参数叫做联系人,类型为List

public class ContactList {
    public List<Contact> contacts { get; set; }
}

然后序列化ContactList对象。

答案 1 :(得分:0)

尝试这样写。确定你会得到你的结果。我在列表中添加了一个项目。你可以添加多个项目。

   void getAllContact()
        {
            Dictionary<string, List<Contact>> contactsDic = new Dictionary<string, List<Contact>>();
            List<Contact> list = new List<Contact>();

            list.Add(new Contact
            {
                ContactID = Guid.Parse("7abe6291-43f2-e411-b150-000c2975315f"),
                Name = "Visitor 1",
                RegID = "1",
                MobileNumber = "1122334455",
                Tel = "1122334455"
            }
            );
            contactsDic.Add("contacts", list);

            string ss = JsonConvert.SerializeObject(contactsDic);
        }

答案 2 :(得分:0)

如果你的模型是Contact class,那么Simplify就是这样做的:

return Ok(new {contacts = yourmodel});