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 的任何示例。
<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:
NamingStrategyType and NamingStrategyParameters allow control of casing and name-mapping of dictionary keys.
For instance, the following dictionary will always serialize its keys literally, without renaming, even if CamelCasePropertyNamesContractResolver is in use:
<JsonDictionary(NamingStrategyType := GetType(LiteralKeyDictionaryNamingStrategy))> _
Public Class LiteralKeyDictionary(Of TValue)
Inherits Dictionary(Of String, TValue)
End Class
Public Class LiteralKeyDictionaryNamingStrategy
Inherits DefaultNamingStrategy
Public Sub New()
ProcessDictionaryKeys = False
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)ItemConverterType, ItemConverterParameters, ItemIsReference, ItemReferenceLoopHandlingand ItemTypeNameHandling allow customization of how dictionary values are serialized.
For instance, in the following dictionary type, the values are always stored with reference preservation enabled:
<JsonDictionary(ItemIsReference := true)> _
Public Class ReferenceObjectDictionary(of TKey, TValue As {Class, New})
Inherits Dictionary(Of TKey, TValue)
End Class
Run Code Online (Sandbox Code Playgroud)
Or, for a dictionary type containing enum values, you might apply StringEnumConverter as an ItemConverterType to force the values to be serialized as strings.
| 归档时间: |
|
| 查看次数: |
2617 次 |
| 最近记录: |