将 JsonDictionary 属性应用于字典

And*_* R. 2 .net c# vb.net json.net

如果我尝试将 JsonDictionary 属性添加到 .net Dictionary(Of Integer, MyClass),编译器会告诉我,无法应用该属性。为什么是这样?

<JsonDictionary()>
Public ReadOnly Property monatswerte As Dictionary(Of Integer, MyClass)
Run Code Online (Sandbox Code Playgroud)

我基本上找不到有关如何在线使用 JsonDictionary 的任何示例。

dbc*_*dbc 5

<JsonDictionary()> can be applied to a type (a class or interface) to force Json.NET's default contract resolver (and its subclasses) to generate a dictionary contract for the type. It is part of a family of three similar attributes:

  • <JsonObject()>. Force a type to be serialized as a JSON object. Useful to force serialization of collection properties instead of items as shown here.
  • <JsonArray()>. Force a type to serialized as a JSON array. Possibly useful to, e.g., force a dictionary to be serialized as a key/value pair array.
  • <JsonDictionary()>. Force a type to be interpreted as a dictionary and serialized as a JSON object. (It must still implement IDictionary or IDictionary<TKey, TValue> for this to work, of course.)

On the face of it <JsonDictionary()> does not seem that useful because DefaultContractResolver.CreateContract(Type objectType) checks that the incoming type implements IDictionary before checking for any other interface implementations. However, the attribute has several properties that could be useful in customizing how a dictionary is serialized, including: