动态地将JSON结构转换为数组

时间:2019-02-27 00:35:14

标签: c# json

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

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

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

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

public class result
{

        public string name { get; set; }

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

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

4 个答案:

答案 0 :(得分:0)

您需要使用Newtonsoft.JSON包。

        var respStr = @"{
                        name:'test',
                        clients: {
                            'client1': 'Bill',
                            'client2': 'Steve',
                            'client3': 'Ryan'
                            }
                        }";
        var jsonObject = JObject.Parse(respStr);
        foreach (var item in jsonObject)
        {
            var name = item.Key;
            JToken token = item.Value;
            if (token is JObject)
            {
                foreach (var clientToken in token)
                {
                    if (clientToken is JProperty)
                    {
                        var clientStr = (clientToken as JProperty).Value;
                    }
                }
            }
            if (token is JValue)
            {
                var value = token.Value<string>();
            }
        }

答案 1 :(得分:0)

您可以将客户端声明为对象数组以实现该目标。

public class result
{

    public string name { get; set; }

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

为了获得客户端名称,您可以遍历对象数组属性名称。您可以参考下面的链接来实现这一目标。

Get properties and values from unknown object

答案 2 :(得分:0)

我会用...

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

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

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);
}

产生相同的输出

答案 3 :(得分:0)

看起来客户列表实际上是一个键集合,也就是字典。所以您可以这样表示:

public class Foo
{
    public string name;
    public Dictionary<string, object> clients;
}

反序列化和迭代如下:

var input = @"{""name"":""test"",""clients"": {""client1"": {""id"": ""1"", ""count"": ""41""},""client2"": {""name"": ""testName""},""client3"": {""CustomerID"": ""a1"", ""internalID"": ""testID""}}}";
var foo = JsonConvert.DeserializeObject<Foo>(input);
foreach (var item in foo.clients)
{
    Console.WriteLine(item.Key);
}

输出:

client1
client2
client3

https://support.airtable.com/hc/en-us/articles/218734758-A-beginner-s-guide-to-many-to-many-relationships]