使用c#解析JSON

时间:2018-04-03 07:14:44

标签: c# json json.net

我一直在使用NewtonSoft JSON Convert库来解析JSON字符串并将其转换为C#对象。我无法将其转换为C#对象,因为我无法从这个JSON字符串中创建一个C#类。

这是JSON字符串:

{  
   "appId":"G9RNVJYTS6SFY",
   "merchants":{  
      "RZX9YMHSMP6A8":[  
         {  
            "objectId":"A:G9RNVJYTS6SFY",
            "type":"DELETE",
            "ts":1522736100111
         }
      ],
      "MNOVJT2ZRRRSC":[  
         {  
            "objectId":"A:G9RNVJYTS6SFY",
            "type":"CREATE",
            "ts":1522736100111
         }
      ]
   },
   ... and so on
}

名称RZX9YMHSMP6A8和MNOVJT2ZRRRSC从请求变为请求

USED

var dict = JsonConvert.DeserializeObject<Dictionary<string, RootObject>>(JSON);

执行此行时出现异常

转换值时出错&#34; G9RNVJYTS6SFY&#34;输入&#39; RootObject&#39;。路径&#39; appId&#39;,第1行,第24位。

public class Merchant
{
    public string objectId
    {
        get;
        set;
    }
    public string type
    {
        get;
        set;
    }
    public long ts
    {
        get;
        set;
    }
}

public class Merchants
{
    public List<Merchant> merchant
    {
        get;
        set;
    }
}

public class RootObject
{
    public string appId
    {
        get;
        set;
    }
    public Merchants merchants
    {
        get;
        set;
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用Dictionary将此json转换为c#类结构来保存商家(其中ID为string键):

public class RootObject
{
    public string AppId { get; set; }
    public Dictionary<string, List<ChildObject>> Merchants { get; set; }
}

public class ChildObject
{
    public string ObjectId { get; set; }
    public string Type { get; set; }
    public long Ts { get; set; }
}

然后您可以循环遍历子对象:

foreach (var kvp in rootObject.Merchants) 
{
    var childObjects = kvp.Value;
    foreach (var childObject in childObjects) {
        Console.WriteLine($"MerchantId: {kvp.Key}, ObjectId: {childObject.ObjectId}, Type: {childObject.Type}");
    }
}