ServiceStack.Text Serial Dictionaries

I used Json.Net to serialize dictionaries of type Dictionary, and when I added integers or logical words to the dictionary, when deserializing I got integers and logical values. Now I was trying to change my code to use ServiceStack.Text instead due to a problem in another part of the code with serializing dates, but now I get the boolean values ​​of integers as strings after deserialization. Is there a way to have the same behavior as Json.Net?

Here is the code to play it: https://gist.github.com/1608951 Test_JsonNet passes, but both Test_ServiceStack_Text_TypeSerializer and Test_ServiceStack_Text_JsonSerializer fail

+4
source share
2 answers

This is a targeted design decision that no type information is selected for primitive value types, so the values ​​remain as strings.

You either have to deserialize into a strongly typed POCO that contains type information:

public class MixType { public string a { get; set; } public int b { get; set; } public bool c{ get; set; } } var mixedMap = new Dictionary<string, object> { { "a", "text" }, { "b", 32 }, { "c", false }, }; var json = JsonSerializer.SerializeToString(mixedMap); Console.WriteLine("JSON:\n" + json); var mixedType = json.FromJson<MixType>(); Assert.AreEqual("text", mixedType.a); Assert.AreEqual(32, mixedType.b); Assert.AreEqual(false, mixedType.c); 

Or deserialize in Dictionary<string,string> and parse it yourself.

Or deserialize using the dynamic ServiceStack API. See the ServiceStack Dynamic JSON Test folder for an example on how to do this.

+4
source

Now you can do this:

 JsConfig.TryToParsePrimitiveTypeValues = true; 

Which will make the JSON deserializer try to determine what types should be, and you will return the integers as integers, booleans back as booleans, etc.

+4
source

Source: https://habr.com/ru/post/1390801/


All Articles