DataContractJsonSerializer ReadObject()返回null值

时间:2014-10-06 05:06:03

标签: asp.net .net json

我正在尝试反序列化JSON数据,以便我可以将值插入到我的数据库中,但我一直在sts.text中获取空值。有人可以帮忙吗?感谢

这是我的数据合同

[DataContract]
internal class Statuses
{
    [DataMember(Name = "text", IsRequired = false)]
    internal string text;
}


        try
        {
            HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
            Stream dataStream = webResponse.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Statuses));
            MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(responseFromServer));

            Statuses sts = (Statuses)js.ReadObject(ms);                
            Console.WriteLine("text: " + sts.text);

        }
        catch (Exception ex)
        {
        }

1 个答案:

答案 0 :(得分:0)

这对我有用:

    // Read the content.
    const string responseFromServer = "{\"text\":\"testing\"}"; //Add JSON

    var js = new DataContractJsonSerializer(typeof(Statuses));
    var ms = new MemoryStream(Encoding.UTF8.GetBytes(responseFromServer));

    var sts = (Statuses)js.ReadObject(ms);
    Response.Write("text: " + sts.text);

另外值得注意的是,我使用公共访问修饰符

转换了内部访问修饰符
[DataContract]
public class Statuses
{
    [DataMember(Name = "text", IsRequired = false)]
    public string text;
}

还要注意我改变了:

System.Text.ASCIIEncoding.ASCII.GetBytes(responseFromServer)

使用:

Encoding.UTF8.GetBytes(responseFromServer)

我从测试中得到的最终结果是:

text:testing