簡體   English   中英

將對象序列化為JSON

[英]To serialize the object into JSON

下面是我的對象代碼

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

            };

序列化后會提供以下JSON格式,

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

我將如何在對象中采用多個系列名稱,以便輸出如下:

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

這是一種方法:

為您的對象創建類:

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

序列化它:

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]}
          ]}

更新:

我不知道它是否適合您的需求,但這是另一種方法:

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

如果我理解正確,那么使用JavaScriptSerializer序列化自定義集合就不需要特別考慮。 試試這種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM