【问题标题】:C# How to deserialize json object to stringC#如何将json对象反序列化为字符串
【发布时间】:2015-04-24 09:42:15
【问题描述】:

我正在尝试将 json 对象反序列化为来自 web 服务的字符串,但我无法做到。 我试图将 [IgnoreDataMember] 属性设置为 null。

我要去这个:

DataContractJsonSerializer MySerializer = new DataContractJsonSerializer(typeof(Response));
Response response = (Response)MySerializer.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(e.Result)));

这是我的响应类:

public class Reponse
{
    [DataMember]
    public data1 { get; set; }

    [DataMember]
    public List<AnotherData> data2 { get; set; }
}

public class AnotherData
{
      [DataMember]
       public string name { get; set; }

       public object object1 {get; set;}

}

我想将名为 object1 的 JSON 对象反序列化为字符串而不是对象。我该怎么做?

感谢您的帮助

【问题讨论】:

  • 这是一个很好的序列化示例。但我想反序列化。
  • JSON 是什么样的?在 JSON 中,"object1" 是否只有一个字符串值,还是它的值是一些嵌套的 JSON 对象或数组?

标签: c# json serialization json-deserialization


【解决方案1】:

您应该使用继承自 IDispatchMessageFormatter 的自定义调度程序创建自定义行为。请收下这个exemple 并更新它。

在 DeserializeRequest 方法中,您将阅读消息:

var bodyReader = message.GetReaderAtBodyContents();
        bodyReader.ReadStartElement("Binary");
        byte[] rawBody = bodyReader.ReadContentAsBase64();
        MemoryStream ms = new MemoryStream(rawBody);
        StreamReader sr = new StreamReader(ms);
        string content = string.Empty;
        using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
        {
            content = reader.ReadToEnd();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2019-05-30
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多