使用Windows Phone中的DataContractJsonSerializer将JSON反序列化为Dictionary

时间:2013-03-05 07:23:04

标签: c# json windows-phone-7 dictionary deserialization

我有一个json字符串,例如

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

我想用DataContractJsonSerializer将其反序列化到我的班级:

[DataContract]
public class MyClass
{
    [DataMember(Name = "timestamp")]
    public int Timestamp { get; set; }

    [DataMember(Name = "features")]
    public Dictionary<string, bool> Features { get; set; }
}

但我在进程"ArgumentException"中遇到错误。我有反序列化Dictionary的问题,如果只反序列化时间戳,那么我没有错误。我认为这是字典最合适的结构。但它不起作用。我检查了this answer on SO,但Dictionary<string, object>也不起作用。 也许是因为在例子中使用:

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

但我无法在Windows Phone中使用DataContractJsonSerializerSettings

抱歉,如果我的问题是双倍的话。

感谢提前。

1 个答案:

答案 0 :(得分:0)

@Alexandr

我正在为您编写代码,它将帮助您将对象从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返回类型创建简单方法。