Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize from C# to JSON a list containing a list containing an array?

Tags:

json

c#

I wish to serialize from C sharp to JSON. I would like the output to be

[
    [
        { "Info": "item1", "Count": 5749 },
        { "Info": "item2", "Count": 2610 },
        { "Info": "item3", "Count": 1001 },
        { "Info": "item4", "Count": 1115 },
        { "Info": "item5", "Count": 1142 },
        "June",
        37547
    ],
    "Monday",
    32347
]

What would my data structure in C# look like?

Would I have something like

public class InfoCount
{
    public InfoCount (string Info, int Count)
    {
        this.Info = Info;
        this.Count = Count;
    }
    public string Info;
    public int Count;
}
List<object> json = new List<object>();
json[0] = new List<object>();
json[0].Add(new InfoCount("item1", 5749));
json[0].Add(new InfoCount("item2", 2610));
json[0].Add(new InfoCount("item3", 1001));
json[0].Add(new InfoCount("item4", 1115));
json[0].Add(new InfoCount("item5", 1142));
json[0].Add("June");
json[0].Add(37547);
json.Add("Monday");
json.Add(32347);

? I am using .NET 4.0.

like image 658
John Avatar asked Nov 24 '25 09:11

John


1 Answers

I would try using anonymous types.

var objs = new Object[]
{
    new Object[]
    {
        new { Info = "item1", Count = 5749 },
        new { Info = "item2", Count = 2610 },
        new { Info = "item3", Count = 1001 },
        new { Info = "item4", Count = 1115 },
        new { Info = "item5", Count = 1142 },
        "June",
        37547
    },
    "Monday",
    32347
};

String json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(objs);

The variable json now contains the following:

[[{"Info":"item1","Count":5749},{"Info":"item2","Count":2610},{"Info":"item3","Count":1001},{"Info":"item4","Count":1115},{"Info":"item5","Count":1142},"June",37547],"Monday",32347]
like image 179
dana Avatar answered Nov 26 '25 23:11

dana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!