Convert list object to json in c #

I have an object model that looks like this:

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

      

I need OUTPUT:

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

      

+3


source to share


1 answer


you can use this workaround if it meets your needs please let me know if it works



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

      

-2


source







All Articles