简体   繁体   English

如何将JSON反序列化为C#词典?

[英]How do I deserialize JSON into a C# Dictionary?

Problem 问题

Heres my JSON object: 这是我的JSON对象:

{
    "1000":{
               "id": "23445",
               "latlon": "6780" 
           },
    "1001":{
               "id": "23454",
               "latlon": "6784" 
           },
    "1002":{
               "id": "23245",
               "latlon": "6180" 
           },
    "1003":{
               "id": "12345",
               "latlon": "6740" 
           }
}

As you can see the property names are pure integers (1000, 1001, 1002, 1003) 如您所见,属性名称是纯整数(1000、1001、1002、1003)

I can't declare class variable names in integar and run System.json.Serialization. 我无法在integar中声明类变量名称,无法运行System.json.Serialization。

Therefore I need to load the JSON file into: 因此,我需要将JSON文件加载到:

public static Dictionary<int, NodeDetail> NodeInfo;

public class NodeDetail {
    public ulong id;
    public int latlon;

    //Generic class serializer

    //Generic class deserializer
}

Is there a library function for this? 是否为此提供库功能? or do I have to parse the JSON string from ground up? 还是我必须从头开始解析JSON字符串?

ps. ps。 I'm new to C#(coming from C++) 我是C#的新手(来自C ++)

Newtonsoft.Json. Newtonsoft.Json。 You can pull it from NuGet. 您可以从NuGet中拉出它。

Simple example: 简单的例子:

public static T DeserializeJson<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json);
}

and then 接着

Dictionary<string, object> foo = DeserializeJson<Dictionary<string, object>>(" ... insert JSON here ... ");

EDIT: given the structure you mention in your question, you may want to deserialize into a nested dictionary: 编辑:给定您在问题中提到的结构,您可能需要反序列化为嵌套字典:

Dictionary<int, Dictionary<long, int>> foo = DeserializeJson<Dictionary<int, Dictionary<long, int>>>(" ... insert JSON here ...");

There's also JObject (in the same Newtonsoft.Json library) which is very helpful for deserializing to something uniform that can be used. 还有一个JObject(在同一Newtonsoft.Json库中)对于将反序列化为可以使用的统一格式非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM