本文介绍了我该如何反序列化动态(数字)键名称的子对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么可以反序列化这个JSON数据?钥匙100034等,实际上是动态的。

How can I deserialize this JSON data? The keys "100034" etc. are dynamic in nature.

{
    "users" : {
        "100034" : {
            "name"  : "tom",
            "state" : "WA",
            "id"    : "cedf-c56f-18a4-4b1"
        },
        "10045" : {
            "name"  : "steve",
            "state" : "NY",
            "id"    : "ebb2-92bf-3062-7774"
        },
        "12345" : {
            "name"  : "mike",
            "state" : "MA",
            "id"    : "fb60-b34f-6dc8-aaf7"
        }
    }
}

有没有一种方法,我可以直接访问每个有对象的名称,状态和Id

Is there a way I can directly access each object having name, state and Id?

推荐答案

声明你这样的课程?

class RootObject
{
    public Dictionary<string, User> users { get; set; }
}

class User
{
    public string name { get; set; }
    public string state { get; set; }
    public string id { get; set; }
}



反序列化是这样的:

Deserialize like this:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);



演示:

Demo:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""users"": {
                ""10045"": {
                    ""name"": ""steve"",
                    ""state"": ""NY"",
                    ""id"": ""ebb2-92bf-3062-7774""
                },
                ""12345"": {
                    ""name"": ""mike"",
                    ""state"": ""MA"",
                    ""id"": ""fb60-b34f-6dc8-aaf7""
                },
                ""100034"": {
                    ""name"": ""tom"",
                    ""state"": ""WA"",
                    ""id"": ""cedf-c56f-18a4-4b1""
                }
            }
        }";

        RootObject root = JsonConvert.DeserializeObject<RootObject>(json);

        foreach (string key in root.users.Keys)
        {
            Console.WriteLine("key: " + key);
            User user = root.users[key];
            Console.WriteLine("name: " + user.name);
            Console.WriteLine("state: " + user.state);
            Console.WriteLine("id: " + user.id);
            Console.WriteLine();
        }
    }
}



输出:

Output:

key: 10045
name: steve
state: NY
id: ebb2-92bf-3062-7774

key: 12345
name: mike
state: MA
id: fb60-b34f-6dc8-aaf7

key: 100034
name: tom
state: WA
id: cedf-c56f-18a4-4b1

这篇关于我该如何反序列化动态(数字)键名称的子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 13:16