DIRTY JSON创造必须有更好的方法

时间:2015-03-05 00:41:35

标签: c# .net json

这可行,但是很乱。我一定是做错了。

    DSDSUser user =     userFactory.GetUserByUsername(HttpContext.Current.User.Identity.Name);
            var messages = user.SystemUser.MessageStages;


            var ret = "[" + messages.Aggregate("", (current, message) => current + (@"[""" + message.Id.ToString() + @""",""" + message.Name + @"""]" + ",")).TrimEnd(',') + "]";

            context.Response.ContentType = "application/json";
            context.Response.Write(ret);

>>>>>>>> 
[
  ["111","Call to members"],
  ["112","Real Estate"],
  ["113","Call to sale"],
  ["131","Snowy Day"],
  ["123","No school today"],
  ["101","Last payment"],
  ["145","Turn off notice"],
  ["113","Bill Collection"],
  ["167","Message default"],
  ["233","Message default"],
  ["323","Message default"],
  ["233","VM message"]  
]
  
    
      

必须有一种更清洁的方法来制作这个Json

    
  

1 个答案:

答案 0 :(得分:0)

通过Visual Studio中的包管理器控制台安装Json.Net:

PM> Install-Package Newtonsoft.Json -Version 6.0.8

然后使用以下命令序列化您的对象:

string json = JsonConvert.SerializeObject(messages);

您可以将[JsonIgnore]添加到您不希望序列化的MessageStages对象上的任何字段。