反序列化混合类型的JSON数组 [英] Deserializing a JSON array of mixed types

查看:264
本文介绍了反序列化混合类型的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法反序列化使用DataContractJsonSerializer类混合类型的JSON阵列。我花了很多时间寻找一个解决方案都无济于事,所以我想我会继续前进,在这里问。

I'm having trouble deserializing a JSON array of mixed types using the DataContractJsonSerializer class. I've spent a bunch of time looking for a solution to no avail, so I thought I'd go ahead and ask here.

基本上,我得到一个JSON串类似下面。我想获取数组反序列化到一个列表,其中0位置有一个Int32,1位有一个字符串和位置2有我的自定义类的一个实例。

Basically, I am getting a JSON string like the one below. I'd like to get the array to deserialize into an List where position 0 has an Int32, position 1 has a String, and position 2 has an instance of my custom class.

[
   2,
   "Mr. Smith",
   {
      "num":169,
      "name":"main street",
      "state":66
   }
]

如果我只创建一个序列化,像这样:

If I just create a serialize like so:

DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<object>))

其实,我在位置0获得一个Int32,并在位置1的String但是在位置2我只是得到一个空对象。

I actually get an Int32 at position 0 and a String at position 1. However at position 2 I just get a null object.

有谁知道什么,我试图做甚至有可能?我有超过我正在消耗JSON的结构没有控制权。我想做到这一点,而无需使用第三方组件如果可能的话。

Does anyone know if what I am trying to do is even possible? I have no control over the structure of the JSON that I'm consuming. I'd like to accomplish this without using third party assemblies if possible.

推荐答案

您不得不做出这样的再现JSON类结构是这样的:

You have to make a class that reproduces the json structure like this:

[DataContract]
public class MyClass {
    [DataMember]
    public int IntMember { get; set; }
    [DataMember]
    public string StringMember { get; set; }
    [DataMember]
    public MyType[] AllTypes { get; set;}
}

[DataContract]
public class MyType {
    [DataMember]
    public int num { get; set; }
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public int state { get; set;}
}



装饰类和它的属性与DataContract和数据成员属性。然后在反序列化的代码使用您在下面的例子中创建的类<​​/ p>

Decorate the class and its properties with the "DataContract" and "DataMember" attributes. Then in your deserializing code use the class you have created as in the following example

var serializer = new DataContractJsonSerializer(typeof(MyClass));
System.IO.StringReader reader = new System.IO.StringReader(jsonData);
System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.Default.GetBytes(jsonData));
return serializer.ReadObject(ms) as MyClass;

这篇关于反序列化混合类型的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆