[英]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.
希望以上任何帮助。
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. 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. [JsonExtensionData]
as @dbc suggested. [JsonExtensionData]
。 See How to serialize a Dictionary as part of its parent object using Json.Net .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.