Reputation: 660
I am using ServiceStack to serialize/deserialize JSON requests. What I am looking to do is take a complex JSON object (with nested objects) and convert it to a Dictionary of nested objects (Dictionary).
For example, if I have a JSON object like:
{ a: "myA",
b: { "myB", true}
}
I want a Dictionary to reflect that. So for each key/value:
key: a value: myA
key: b value: Dictionary<string, object>
key: myB value: true
I've tried
var dict = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(request);
and
var dict = JsonObject.Parse(request);
What I end up getting is:
key: a value: myA
key: b value: "myB:true"
Note I need this to work for infinite nested Json objects (i.e. I could have 3, 4, or even 5 levels deep).
Upvotes: 2
Views: 2677
Reputation: 3043
i tried to do this for a custom session state module, and there are many edge cases you have to consider when serializing an object that you need the type data for into JSON, which by default has no notion of type. One easy way to do it is to force ServiceStack to serialize type information into the JSON by using
JSConfig.includeTypeInfo = true;
In your AppHost initialize method. This will tell ServiceStack to include the "__type" property into every single object it serializes to JSON, including strings and ints and basic types. This represents a lot of overhead, especially if you are in a large project that does not need type information for every single serialization.
Alternatively, you will have to implement your own type system if you want it just for this one nested object Dictionary
. I ended up doing this and it took a while to get right.
Lastly, there's this post from Mythz (lead of ServiceStack) which says that if you serialize it as an interface, it will include type information. I have independently verified this to be the case, so if you have control over what is going into the nested Dictionary and can restrict them all to one interface, you can make it work.
type info in ServiceStack JSON
Upvotes: 3