简体   繁体   English

ServiceStack.Text JsonObject和数组

[英]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. 我有以下代码,其中ServiceStack.Text使实际上应该是数组的对象变成字符串。

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? 如何访问阵列内容?

ServiceStack.Text.JsonObject is a Dictionary<string, string> thus it doesn't act is you expected.. ServiceStack.Text.JsonObjectDictionary<string, string>因此您期望它不起作用。

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. 您不能使2个不同的json结构反序列化到同一对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM