转换列表对象JSON在C#

问题描述:

我有一个对象模型,看起来像这样:转换列表对象JSON在C#

public class Myclass 
{ 
    public int Id { get; set; } 
    public string name { get; set; } 
    public int age { get; set; } 
} 

public ContentResult GetList(List<Myclass> model) 
{ 

    var list = JsonConvert.SerializeObject(
     model, 
     Formatting.Indented, 
     new JsonSerializerSettings() 
     { 
      ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore 
     }); 

    return Content(list, "application/json"); 
} 

我需要OUTPUT:

[[1,"name1",23],[2,"name2",30],[3,"name3",26],[4,"name4",29]] 
+1

您需要提供更好的细节,你正在得到什么......你在所需的输出显示的JSON是无效的JSON,一个d从你的代码很可能你实际上得到正确的JSON –

+2

我应该澄清 - 当我说它是无效的JSON我的意思是它并不代表JSON绑定到任何类型的对象结构。 –

+0

如果你不需要像'ReferenceLoopHandling'这样的特殊设置(它看起来你没有这样做),你可以'返回Json(模型);'而不用显式序列化(只返回'JsonResult'而不是'ContentResult') –

您可以使用此解决方案,如果它满足您的需求,请让我知道如果这个作品

 List<Myclass> model = new List<Myclass>(); 
     model.Add(new Myclass() { Id = 1, Name = "Name1", Age = 50 }); 
     model.Add(new Myclass() { Id = 2, Name = "Name2", Age = 51 }); 
     model.Add(new Myclass() { Id = 3, Name = "Name3", Age = 52 }); 

     string json = JsonConvert.SerializeObject(model); 
     //If you want to replace { with [ and } with ] 
     json = json.Replace("{", "[").Replace("}", "]"); 

     //you can use this workaround to get rid of property names 
     string propHeader = "\"{0}\":"; 

     json= json.Replace(string.Format(propHeader, "Id"), "") 
      .Replace(string.Format(propHeader, "Name"),"") 
      .Replace(string.Format(propHeader, "Age"), ""); 

     Console.WriteLine(json);