[英]How to use DataContractJsonSerializer to parse a nested json object?
I have a json text like this: 我有一个像这样的json文本:
{
"response":200,
"result":
{
"package":
{
"token":"aaa"
}
}
}
I am using DataContractJsonSerializer to extract info from this above json. 我正在使用DataContractJsonSerializer从上面的json中提取信息。
public static T Deserialize<T>(string json)
{
var instance = Activator.CreateInstance<T>();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(instance.GetType());
return (T)serializer.ReadObject(ms);
}
}
I describe the classes as follow: 我将课程描述如下:
[DataContract]
class IttResponse
{
[DataMember(Name = "response")]
public int Response { get; protected set; }
[DataMember(Name = "result")]
public string Result { get; protected set; }
}
[DataContract]
public class IttPackage
{
[DataMember(Name = "token")]
public string Token { get; set; }
}
Now, I tried to parse the json text as follow: 现在,我尝试解析json文本如下:
IttResponse response = Deserialize<IttResponse>(jsonText);
IttPackage package = Deserialize<IttPackage>(response.token);
However, I always get error when parsing jsonText at the first line. 但是,在第一行解析jsonText时总是会出错。
Note: I am developing an application running on desktop written in C#, VS Ultimate 2013, .Net Framework 4.5 注意:我正在开发一个在C#,VS Ultimate 2013,.Net Framework 4.5上编写的桌面上运行的应用程序
So, I think, I cannot use System.Web.Helpers , or System.Web.Script.Serialization to parse. 所以,我认为,我不能使用System.Web.Helpers或System.Web.Script.Serialization来解析。
The serialization engine understands complex types. 序列化引擎了解复杂类型。 It's safe for one DataContract type to reference another DataContract type. 一个DataContract类型引用另一个DataContract类型是安全的。
(edit: I'm not entirely sure if protected setters are allowed) (编辑:我不完全确定是否允许受保护的setter)
[DataContract]
class IttResponse
{
[DataMember(Name = "response")]
public int Response { get; protected set; }
[DataMember(Name = "result")]
public IttResult Result { get; protected set; }
}
[DataContract]
public class IttResult
{
[DataMember(Name = "package")]
public IttPackage Package { get; set; }
}
[DataContract]
public class IttPackage
{
[DataMember(Name = "token")]
public string Token { get; set; }
}
Usage remains the same as before 用法与以前一样
IttResponse response = Deserialize(jsonText);
You can include your IttPackage
into IttResposne
object so that you will only parse json one time. 您可以包括你的IttPackage
到IttResposne
对象,这样你就只解析JSON一次。 Moreover, I don't think you can use protected
modifier for property's set
method, so try removing it. 此外,我不认为你可以使用protected
modifier作为属性的set
方法,所以尝试删除它。
[DataContract]
class IttResponse
{
[DataMember(Name = "response")]
public int Response { get; set; }
[DataMember(Name = "result")]
public string IttPackage Result{ get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.