我将下面的数据作为JSON对象:
{"Data1":
{"id":1,
"last":"0.00000045"},
"Data2":
{"id":2,
"last": "0.02351880"}}
将c#转换为JSON数组以下的最佳方法是什么:
[{"name":"Data1",
"id":1,
"last":"0.00000045"},
{"name":"Data2",
"id":2,
"last": "0.02351880"}]
提前致谢,
iziz1
答案 0 :(得分:3)
您可以尝试以下代码;
首先,为反序列化创建模型类
public class Data
{
public int id { get; set; }
public string last { get; set; }
}
public class DataWithKey
{
public string name { get; set; }
public int id { get; set; }
public string last { get; set; }
}
然后将原始Json反序列化为Dictionary<string, Data>
并转换为所需列表; (需要Json.NET)
var dataAsList = JsonConvert.DeserializeObject<Dictionary<string, Data>>(json).Select(x => new DataWithKey
{
name = x.Key,
id = x.Value.id,
last = x.Value.last
}).ToList();
var convertedJson = JsonConvert.SerializeObject(dataAsList); //Desired json
<强>输出:强>
[
{
"name":"Data1",
"id":1,
"last":"0.00000045"
},
{
"name":"Data2",
"id":2,
"last":"0.02351880"
}
]
答案 1 :(得分:0)
使用DataContractJsonSerializer类来序列化和反序列化json数据。