0

I have the following code where ServiceStack.Text make the objects which should actually be an array become a string.

var json1 = "{\"x\": [1, 2, 3]}";
var o1 = JsonSerializer.DeserializeFromString<JsonObject>(json1);
var isString1 = o1["x"].GetType() == typeof(string); // Why string and not an array?

var json2 = "{\"x\": [{ \"a\" : true}]}";
var o2 = JsonSerializer.DeserializeFromString<JsonObject>(json2);
var isString2 = o1["x"].GetType() == typeof(string); // Why string and not an array?

What can I do, so that it will be an array? How can I access the array contents?

1 Answer 1

1

ServiceStack.Text.JsonObject is a Dictionary<string, string> thus it doesn't act is you expected..

public class JsonObject : Dictionary<string, string>

Deserialization job isn't to guess your target type, it assume you know the structure and by assumption it doing it's magic to make it your intended Type.

You can not make 2 different json structure to deserialize to the same object.

The following will work for the 1st example:

var o1 = JsonSerializer.DeserializeFromString<Dictionary<string, int[]>>

The 2nd example should have a different type, and the following will work, but i would suggest you to write a specific class model for it, the following is very general:

var o2 = JsonSerializer.DeserializeFromString<Dictionary<string, Dictionary<string, bool>[]>>(json2);
Sign up to request clarification or add additional context in comments.

4 Comments

When I receive dynamic json input I cannot predefine a class structure. How would i process such dynamic input? How would I programatically find out that there is an array in the json?
JSONs are manifest of actual types, the types should be known, You don't need to predict nothing because a real API service will have a constant structure for every action. actions may have different types, but for every action you should know the resulted json, otherwise it's API made by amateur, which assume you know how the returned structure should be, which is a coupled API a violation of the Separation of Concerns.
Still, I expected JsonObject to represent the complete json object hierarchy as some other Json Libraries do. So there is no way to iterate over the contents of this JsonObject with ServiceStack?
JsonObject is a Dictionary<string, string> then how you expect it to be any other type than a string ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.