2

I have a json string, for example

{"timestamp":1362463455, "features" : {"one":true, "two":false}}

I want to deserialize it with DataContractJsonSerializer to my class:

[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". I have a problems with deserialize Dictionary, if deserialize only timestamp then I don't have errors. 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. Maybe because in example using:

DataContractJsonSerializerSettings settings =
        new DataContractJsonSerializerSettings();
settings.UseSimpleDictionaryFormat = true;

But I can't use DataContractJsonSerializerSettings in Windows Phone.

Sorry, if my question is double.

Thank advance.

4

1 回答 1

0

@亚历山大

我正在为您编写代码,它将帮助您将对象从 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;
   }
} 

上面的代码在我的 wp8 应用程序中运行,你可以尝试更快,它会对你有所帮助。我正在执行异步操作,但您可以使用 MyClass 返回类型创建简单的方法。

于 2013-11-18T05:39:26.300 回答