简体   繁体   中英

Deserialize JSON to Dictionary with DataContractJsonSerializer in Windows Phone

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.

@Alexandr

I am writing a code for you it will help you to deserialize the object from json to 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. I am performing asynchronous operation but you can create your simple method with MyClass return type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM