Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        去年关闭。
                                                                                            
                
        
我得到以下数据作为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

最佳答案

您可以尝试以下代码;

首先,创建反序列化的模型类

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

关于c# - C#将JSON对象转换为数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48050513/

10-11 22:23
查看更多