JSON数组DataContractJsonSerializer

JSON数组DataContractJsonSerializer

本文介绍了反序列化一个简单的JSON数组DataContractJsonSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这个问题已经被问了一遍又一遍,但由于某些原因,我还是不能设法得到这个工作。

I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.

我要反序列化包含单个成员的JSON对象;一个字符串数组:

I want to deserialize a JSON object that contains a single member; a string array:

{"results" : ["a", "b"]}

这就是我想要反序列化到类:

This is the class that I'm trying to deserialize into:

public class Whatever {
    [DataMember(Name = "results")]
    public string[] Results { get; protected set; }
}

这是Deserialize方法:

And this is the Deserialize method:

private 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);
    }
}

一个电话像反序列化&LT;无论&GT;({\的结果\:\一\,\B \]})正在恢复但结果阵列下榻

A call like Deserialize<Whatever>("{\"results\" : [\"a\", \"b\"]}") is returning an initialized instance of Whatever but the Results array is staying null.

时有什么错?

Is there something wrong with the structure of Whatever?

推荐答案

嗯,发布这个我意识到,我错过了 DataContract 属性装修后无论

Ah, after posting this I realized that I was missing the DataContract attribute decoration on Whatever:

[DataContract]
public class Whatever {
    [DataMember(Name = "results")]
    public string[] Results { get; protected set; }
}

现在它工作正常。

这篇关于反序列化一个简单的JSON数组DataContractJsonSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:11