Reshma
Reshma

Reputation: 904

To serialize the object into JSON

Below is my code for object

var obj_series = new
            {
                name = s_Name,
                data = p_Value

            };

which after serializing gives the below JSON format,

["series":[{"name":"01. Target"}],"data":[14,18,12]}]

How I am going to take multiple series name inside the object so that output can be as follows,

       "series":
        {
            name: 'Target',
            data: [14,18,12]
        }, {
            name: 'Alarm',
            data: [14,18,12]
        }, {
            name: 'Actual',
            data: [14,18,12]
        }

     List<object> modified_listofstrings = new List<object>();
     System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     List<string> s_Name = new List<string>();
     List<float> p_Value = new List<float>();
     modified_listofstrings.Add(obj_series);
     jSearializer.Serialize(modified_listofstrings);

Upvotes: 0

Views: 177

Answers (2)

Mateus Schneiders
Mateus Schneiders

Reputation: 4903

This is one way to do it:

Create classes for your objects:

public class Serie
{
    public string Name { get; set; }
    public List<long> Data { get; set; }

    public Serie()
    {
        Data = new List<long>();
    }
}

public class SeriesCollection
{
    public List<Serie> Series { get; set; }
    public SeriesCollection()
    {
        Series = new List<Serie>();
    }
}

Serialize it:

SeriesCollection collection = new SeriesCollection();

collection.Series.Add(new Serie() { Name = "Target", Data = { 1, 2, 3 } });
collection.Series.Add(new Serie() { Name = "Alarm", Data = { 1, 2, 3 } });
collection.Series.Add(new Serie() { Name = "Actual", Data = { 1, 2, 3 } });

System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string seriesStr = jSearializer.Serialize(collection);

Output:
{"Series":[{"Name":"Target","Data":[1,2,3]},
           {"Name":"Alarm","Data":[1,2,3]},
           {"Name":"Actual","Data":[1,2,3]}
          ]}

UPDATE:

I don't know if it suits your needs, but here is another way:

var seriesdasda = new { series = new List<object>() };
seriesdasda.series.Add(new { name = "Target", data = { 1, 2, 3 }});
seriesdasda.series.Add(new { name = "Alarm", data = { 1, 2, 3 }});
seriesdasda.series.Add(new { name = "Actual", data = { 1, 2, 3 }});

string seriesStr2 = jSearializer.Serialize(seriesdasda);

Upvotes: 1

S.N
S.N

Reputation: 5140

If I get it correct, then there is no special consideration is required in order to serialize a custom collection using JavaScriptSerializer. Try this approach.

Upvotes: 0

Related Questions