动态地将JSON结构转换为数组 [英] dynamically converting a JSON structure to an array

查看:94
本文介绍了动态地将JSON结构转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#代码中,我正在调用一个终结点,该终结点向结构发送回与此类似的内容

In my C# code I am calling an endpoint which sends back the structure something similar to this

{       
       "name":"test",
        "clients": {
            "client1": {"id": "1", "count": "41"},
            "client2": {"name": "testName"},
            "client3": {"CustomerID": "a1", "internalID": "testID"}
        }
}

我需要将其转换为C#对象,然后遍历客户端".问题是,事先我不知道客户端名称(在上面的示例中为"client1","client2"和"client3")或可以返回的客户端数量.

I need to convert this to a C# object and then iterate through the "clients". The problem is that beforehand I do not know the client names (in the above example "client1", "client2", and "client3") or the number of clients that can come back.

所以在我的代码中,我有以下C#文件

So in my code I have the following C# file

public class result
{

        public string name { get; set; }

        [JsonProperty("clients")]
        public string[] clients { get; set; }
}

但是,当我尝试使用JsonConvert.DeserializeObject对此进行解析时,出现错误.理想情况下,我想做的是将客户端转换为C#数组,然后对其进行迭代.

However when I try to parse this using JsonConvert.DeserializeObject I get an error. Ideally what I would like to do is to convert the clients into a C# array and then iterate though them.

推荐答案

我会使用...

public class result
{

    public string name { get; set; }

    [JsonProperty("clients")]
    public Dictionary<string, dynamic> Clients { get; set; }
}

使用代码...

result test = JsonConvert.DeserializeObject<result>(Resource1.JSON);

Console.WriteLine(test.Clients["client1"].id);
Console.WriteLine(test.Clients["client2"].name);
Console.ReadLine();

输出...

1 
testName

或者,如果不确定属性,可以按照以下说明进行调整

Alternatively if you're unsure of the properties you can tweak this as follows

public class result
{

    public string name { get; set; }

    [JsonProperty("clients")]
    public Dictionary<string, ExpandoObject> Clients { get; set; }
}

使用代码...

result  test = JsonConvert.DeserializeObject<result>(Resource1.JSON);

foreach(string key in test.Clients.Keys)
{
    ExpandoObject obj = test.Clients[key];
    var dict = obj as IDictionary<string, object>;
    dynamic client = obj;
    if (dict.ContainsKey("id"))
        Console.WriteLine(client.id);

    if (dict.ContainsKey("name"))
        Console.WriteLine(client.name);
}

产生相同的输出

这篇关于动态地将JSON结构转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆