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?

trenki
  • 7,133
  • 7
  • 49
  • 61

1 Answers1

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);
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • 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? – trenki Jan 17 '16 at 15:31
  • 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. – Orel Eraki Jan 17 '16 at 15:40
  • 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? – trenki Jan 17 '16 at 15:53
  • JsonObject is a `Dictionary` then how you expect it to be any other type than a string ? – Orel Eraki Jan 17 '16 at 16:11