简体   繁体   English

反序列化json的C#最佳对象或类结构

[英]C# Optimal object or class structure for deserialized json

I have a json structured like that: 我有一个像这样的json结构:

{
  "eventType1": {
    "unitName": "nameValue",
    "comment": "initial comment"
  },
  "eventType2": {
    "comment": "initial message"
  },
}

When I deserialize it the appropriate type seems to be something like Dictionary<string, <Dictionary<string,string>>> and method would look like that: 当我反序列化它时,合适的类型似乎像Dictionary<string, <Dictionary<string,string>>> ,方法看起来像这样:

public static Dictionary<string, Dictionary<string, string>> defaultFieldDataByEvent =
        JsonConvert
        .DeserializeObject<Dictionary<string, Dictionary<string, string>>>(defaultFieldDataByEventSerialized);

which looks, well, ugly. 看起来很丑。 But that's exactly how I need it to extract the data - defaultFieldDataByEvent[eventType][field] . 但这正是我需要它提取数据的方式defaultFieldDataByEvent[eventType][field]

Can I encapsulate the type into something somehow or is there a different approach to such cases? 我可以以某种方式将类型封装为某种形式,还是有其他方法可以解决这种情况?

I see multiple possible options here. 我在这里看到多个可能的选择。 Hope any of these helps. 希望以上任何帮助。

  • You may try to add a type alias with using directive to make code shorter, but this won't be convenient, if logic is spread across multiple files, because you will be forced to duplicate this alias. 您可以尝试使用using指令添加类型别名以使代码更短,但是如果逻辑分散在多个文件中,这样做将不方便,因为您将被迫重复使用该别名。
  • You may try to use JObject.Parse for deserialization, staying on lower level. 您可以尝试使用JObject.Parse进行反序列化,将其保持在较低级别。 But as far as your json structure is pretty various, this approach may work well. 但是就您的json结构而言,这种方法可能效果很好。
  • You may try to deserialize your data into ExpandoObject . 您可以尝试将数据反序列化为ExpandoObject It's rather similar to JObject , except you will get pretty nice dynamic code (dynamic is not a problem here since compiler won't help you with Dictionary either), but it, obviously will be less performant. 它与JObject非常相似,除了您将获得非常漂亮的动态代码(这里的动态不是问题,因为编译器也无法为Dictionary帮助),但是显然性能较低。 You could lose your custom types information, since everything in your graph will become an ExpandoObject , but seems like that's not an issue for your case. 您可能会丢失自定义类型信息,因为图形中的所有内容都将变为ExpandoObject ,但是对于您的情况而言,这似乎不是问题。 Example may be found here. 示例可以在这里找到。
  • You may try to use [JsonExtensionData] as @dbc suggested. 您可以尝试按照@dbc的建议使用[JsonExtensionData] See How to serialize a Dictionary as part of its parent object using Json.Net . 请参阅如何使用Json.Net将Dictionary序列化为其父对象的一部分

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

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