[英]Deserialize JSON to Dictionary with DataContractJsonSerializer in Windows Phone
I have a json string, for example 例如,我有一个json字符串
{"timestamp":1362463455, "features" : {"one":true, "two":false}}
I want to deserialize it with DataContractJsonSerializer
to my class: 我想使用
DataContractJsonSerializer
将其反序列化到我的班级:
[DataContract]
public class MyClass
{
[DataMember(Name = "timestamp")]
public int Timestamp { get; set; }
[DataMember(Name = "features")]
public Dictionary<string, bool> Features { get; set; }
}
But I have a error in process "ArgumentException"
. 但是我在处理
"ArgumentException"
出错。 I have a problems with deserialize Dictionary
, if deserialize only timestamp then I don't have errors. 我在反序列化
Dictionary
遇到问题,如果仅对时间戳进行反序列化,则没有错误。 I thought is dictionary most suitable structure for this. 我认为这是字典最合适的结构。 But it don't work.
但这不起作用。 I checked this answer on SO , but
Dictionary<string, object>
don't work too. 我在SO上检查了这个答案 ,但是
Dictionary<string, object>
也不起作用。 Maybe because in example using: 可能是因为在示例中使用:
DataContractJsonSerializerSettings settings =
new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;
But I can't use DataContractJsonSerializerSettings
in Windows Phone. 但是我不能在Windows Phone中使用
DataContractJsonSerializerSettings
。
Sorry, if my question is double. 对不起,如果我的问题是双重的。
Thank advance. 谢谢提前。
@Alexandr @亚历山大
I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject. 我正在为您编写代码,它将帮助您将对象从json反序列化为yourClassCustomObject。
private async Task<List<MyClass>> MyDeserializerFunAsync()
{
List<MyClass> book = new List<MyClass>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<MyClass>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<MyClass>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. 上面的代码在我的wp8应用程序中运行,您可以尝试更快地运行,它将为您提供帮助。 I am performing asynchronous operation but you can create your simple method with MyClass return type.
我正在执行异步操作,但是您可以使用MyClass返回类型创建简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.