JSON.NET deserialize JSON object stored as property

前端 未结 2 1320
死守一世寂寞
死守一世寂寞 2021-01-21 20:27

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
{
    publi         


        
相关标签:
2条回答
  • 2021-01-21 20:31

    You can do this with a custom converter. For example:

    public class EnvelopeConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, 
            JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, 
            object existingValue, JsonSerializer serializer)
        {
            var envelope = JObject.Load(reader);
    
            var type = envelope["Type"].ToString();
            var message = JsonConvert.DeserializeObject<Message>(
                envelope["InnerMessage"].ToString());
    
            return new Envelope
            {
                Type = type,
                InnerMessage = message
            };
        }
    
        public override bool CanRead
        {
            get { return true; }
        }
    
        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }
    

    And use it like this:

    Envelope envelope = JsonConvert.DeserializeObject<Envelope>(
        jsonMessage, new EnvelopeConverter());
    
    0 讨论(0)
  • 2021-01-21 20:43

    You need a custom 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);
        }
    }
    

    and add a JsonConverterAttribute to the InnerMessage property

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

    and now you can serialize/deserialize the Envelope class with

    var envelope = JsonConvert.DeserializeObject<Envelope>( jsonMessage );
    
    0 讨论(0)
提交回复
热议问题