2017-06-02 64 views
3

我有一個對象模型,看起來像這樣:轉換列表對象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') –

回答

-2

您可以使用此解決方案,如果它滿足您的需求,請讓我知道如果這個作品

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