下面是我的对象代码
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);
答案 0 :(得分:1)
这是一种方法:
为对象创建类:
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);
答案 1 :(得分:0)
如果我认为它是正确的,那么为了使用JavaScriptSerializer
序列化自定义集合,不需要特别考虑。尝试this方法。