问题描述
我有一个像这样的json文本:
I have a json text like this:
{
"response":200,
"result":
{
"package":
{
"token":"aaa"
}
}
}
我正在使用DataContractJsonSerializer从json以上的内容中提取信息.
I am using DataContractJsonSerializer to extract info from this above 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);
}
}
我将这些类描述如下:
[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; }
}
现在,我尝试按以下方式解析json文本:
Now, I tried to parse the json text as follow:
IttResponse response = Deserialize<IttResponse>(jsonText);
IttPackage package = Deserialize<IttPackage>(response.token);
但是,在第一行解析jsonText时总是会出错.
However, I always get error when parsing jsonText at the first line.
注意:我正在开发在用C#,VS Ultimate 2013,.Net Framework 4.5编写的桌面上运行的应用程序
Note: I am developing an application running on desktop written in C#, VS Ultimate 2013, .Net Framework 4.5
因此,我认为我无法使用 System.Web.Helpers 或 System.Web.Script.Serialization 进行解析.
So, I think, I cannot use System.Web.Helpers, or System.Web.Script.Serialization to parse.
推荐答案
序列化引擎可以理解复杂的类型.一种DataContract类型引用另一种DataContract类型是安全的.
The serialization engine understands complex types. It's safe for one DataContract type to reference another DataContract type.
(我不确定是否允许受保护的二传手)
[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; }
}
用法与以前相同
IttResponse response = Deserialize(jsonText);
这篇关于如何使用DataContractJsonSerializer解析嵌套的json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!