运行时确定JArray内容类型

时间:2015-03-13 23:58:07

标签: c# json json.net

我必须在运行时确定要在相应方法中使用的JSON JArray对象的类型:

我的部分JSON如下:

{
  "$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib",
  "listdouble": {
    "$type": "System.Collections.Generic.List`1[[System.Double, mscorlib]], mscorlib",
    "$values": [
      1,
      3
    ]
  },
  "listbool": {
    "$type": "System.Collections.Generic.List`1[[System.Boolean, mscorlib]], mscorlib",
    "$values": [
      true,
      false
    ]
  },
  "liststring": {
    "$type": "System.Collections.Generic.List`1[[System.String, mscorlib]], mscorlib",
    "$values": [
      null,
      " ",
      "New String"
    ]
  }
}

这是从Dictionay<string, object>序列化的Json的一部分。在运行时,它被反序列化为字典,其键映射到JArrays。一旦我知道其中包含的数据类型,我就可以在ToObject上使用JArray方法,但是如何确定它由哪种类型组成?比如字典键是映射到List<double>还是List<bool>

1 个答案:

答案 0 :(得分:0)

我要做的是使用动态对象来反序列化JSON,如

dynamic d = JsonConvert.DeserializeObject(jsonString);

然后通过

访问数组
JArray arrayOfDoubles = d.listdouble.values;

并检查包含的类型

List<JTokenType> listOfTypes = arrayOfDoubles.GroupBy(item => item.Type).Select(item => item.Key).ToList();

在这种情况下,listOfTypes的输出是

[0] Integer

但你当然可以从中获得一系列双打。

List<double> listOfDoubles = arrayOfDoubles.ToObject<List<double>>();

结果会很好:

[0] 1.0
[1] 3.0

与你的bool列表相同:

JArray arrayOfBools = d.listbool.values;
listOfTypes = arrayOfBools.GroupBy(item => item.Type).Select(item => item.Key).ToList();

listOfTypes的输出

[0] Boolean

反序列化:

List<bool> listOfBools = a.ToObject<List<bool>>();

输出:

[0] true
[1] true

同样适用于字符串。

您也可以通过

从您提供的类型反序列化数组
var type = d.listdouble.type; // "System.Collections.Generic.List`1[[System.Double, mscorlib]], mscorlib"

var myType = Type.GetType(type.ToString()); // get the type out of it
var myGenericList = arrayOfDoubles.ToObject(myType);

myGenericList的类型为{System.Collections.Generic.List<double>},值为[1.0,3.0]。工作得很好。

因此,您可以针对json数组中的元素检查json类型d.listdouble.type,以确保它将被反序列化。

希望这有帮助!