JSON.NET反序列化存储为属性的JSON对象 [英] JSON.NET deserialize JSON object stored as property

查看:75
本文介绍了JSON.NET反序列化存储为属性的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON消息要反序列化,该字符串属性包含另一个对象的JSON.我有以下课程

I have a JSON message to deserialize with a string property containing the JSON of another object. I have the following classes

public class Envelope
{
    public string Type { get; set; }
    public Message InnerMessage { get; set; }
}

public class Message
{
    public string From { get; set; }
    public string To { get; set; }
    public string Body { get; set; }
}

我收到的JSON消息采用以下格式:

the JSON message I receive is in this format:

{
    Type : "send",
    InnerMessage : "{ From: \"sender\", To: \"receiver\", Body: \"test\" }"
}

请注意,InnerMessage包含Message类的序列化,而不是该类的JSON.

note that InnerMessage contains the serialization of the Message class, not the JSON of the class.

如果将InnerMessage属性的类型保持为Message,则标准JSON.NET反序列化将失败.

If I keep the type of InnerMessage property to Message, the standard JSON.NET deserialization fails.

如果将InnerMessage更改为string,则可以进行序列化,但是在将InnerMessage的内容再次反序列化为Message类之后:

If I change the InnerMessage to string, the serialization works but after I need to deserialize again the content of InnerMessage to Message class:

Envelope envelope = JsonConvert.DeserializeObject<Envelope>(jsonMessage);
Message innerMessage = JsonConvert.DeserializeObject<Envelope>(envelope.InnerMessage);

有什么方法可以将EnvelopeInnerMessage属性保留为Message,并告诉JSON.NET将字符串值自动反序列化?

There is some way to keep the InnerMessage property of Envelope to Message and tell JSON.NET to treat the string value to be deserialized automatically?

推荐答案

您需要自定义JsonConverter

class StringTypeConverter : Newtonsoft.Json.JsonConverter
{
    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string json = (string)reader.Value;
        var result = JsonConvert.DeserializeObject(json, objectType);
        return result;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var json = JsonConvert.SerializeObject(value);
        serializer.Serialize(writer, json);
    }
}

并将JsonConverterAttribute添加到InnerMessage属性

public class Envelope
{
    public string Type { get; set; }
    [Newtonsoft.Json.JsonConverter(typeof(StringTypeConverter))]
    public Message InnerMessage { get; set; }
}

public class Message
{
    public string From { get; set; }
    public string To { get; set; }
    public string Body { get; set; }
}

,现在您可以使用

var envelope = JsonConvert.DeserializeObject<Envelope>( jsonMessage );

这篇关于JSON.NET反序列化存储为属性的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆