trenki
trenki

Reputation: 7363

ServiceStack.Text JsonObject and Arrays

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?

Upvotes: 0

Views: 1347

Answers (1)

Orel Eraki
Orel Eraki

Reputation: 12196

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);

Upvotes: 1

Related Questions