开发者

VB.NET 4.0 DataContractJsonSerializer with changed properties

i have some Objects serialized with the System.Runtime.Serialization.Json.DataContractJsonSerializer and written to my Database:

Dim serializer = New DataContractJsonSerializer(obj.GetType)
Using ms = New MemoryStream()
    serializer.WriteObject(ms, obj)
    ms.Position = 0
    Using sr = New StreamReader(ms)
        Dim json = sr.ReadToEnd()
        sr.Close()
        Return json
    End Using
End Using

Now i have to change the Classes and add some new Properties.

Then i want to deserialize the "old" strings to the new classes:

Using ms = New MemoryStream(Encoding.UTF开发者_运维问答8.GetBytes(serialized))
    Dim ser = New DataContractJsonSerializer(GetType(T))
    Return DirectCast(ser.ReadObject(ms), T)
End Using

How can i now deserialize the "old" Strings to the new class? (The new Properties can stay empty)

thank you!


We found a solution for this issue:

We switched from the DataContractJsonSerializer to JSON.Net. The Problem now was, that the JSON.Net serializes with a different naming conventions, so the old serializes Data in the Database could not be Deserialized. the DataContractJsonSerializer uses "_propertyname", ans the JSON.Net uses "propertyname".

But fortunalety the JSON.Net Serializer allowed us to overwrite the Naming Generation with a small class:

 Public Class UnderscorePropertyNamesContractResolver
    Inherits Newtonsoft.Json.Serialization.DefaultContractResolver

    Protected Overrides Function ResolvePropertyName(propertyName As String) As String
        Return MyBase.ResolvePropertyName("_" + propertyName)
    End Function
End Class

Which could be then used this was with the old JSON Data:

 Dim Setting = New JsonSerializerSettings
 Setting.ContractResolver = New UnderscorePropertyNamesContractResolver
 return JsonConvert.DeserializeObject(Of T)(serialized, Setting)

and do the Seralisation with this:

Dim Setting = New JsonSerializerSettings
Setting.ContractResolver = New UnderscorePropertyNamesContractResolver
return JsonConvert.SerializeObject(obj, Formatting.Indented, Setting)

Now we have a more fault tollerant JSON Serialisation and can add Properties to our classes with the old JSON Data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜