How do I deserialize a property containing an escaped JSON string? [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-31 05:57:28

问题


I have an application/json response from an API that has a property, itself, containing an escaped JSON string.

{
    "id": 0,
    "aggregation_id": "533741f4-49da-4db9-9660-4ca7bafb30e1",
    "task_id": "217",
    "event_type": "discovery",
    "event_name": "device_discovery_complete",
    "method": "ssh",
    "message_details": "{\"aggregation_id\":\"533741f4-49da-4db9-9660-4ca7bafb30e1\",\"ou_id\":0,\"device_id\":13,\"node_id\":13,\"task_id\":217}",
    "time": "2018-01-25T17:59:25"
  }

I want to deserialize the object and the inner object to a model type.

public class Response
{
    public DateTime time {get; set;}
    public string event_name {get; set;}
    public string event_type {get; set;}
    public string method {get; set;}
    public MessageDetails message_details {get; set;}
}

public class MessageDetails
{
    public int device_id {get; set;}
}

Using a call like this

JsonConvert.DeserializeObject<Response>("... response string...");

However, Netwonsoft.Json handles the outer properties just fine, but throws an exception on matching message_details.

Newtonsoft.Json.JsonSerializationException: Error converting value "... response string snipped ..." to type 'RpcApi.Entities.MessageDetails'. 
Path '[0].message_details', line 1, position 390. 
---> System.ArgumentException: Could not cast or convert from System.String to RpcApi.Entities.MessageDetails.

回答1:


You could use a custom JsonConverter for this similar to this:

public class EmbeddedJsonConverter : 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)
    {
        return serializer.Deserialize(new StringReader((string)reader.Value), objectType);
    }

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

Mark the property with [JsonConverter(typeof(EmbeddedJsonConverter))] like:

public class Response
{
    public DateTime time { get; set; }
    public string event_name { get; set; }
    public string event_type { get; set; }
    public string method { get; set; }

    [JsonConverter(typeof(EmbeddedJsonConverter))]
    public MessageDetails message_details { get; set; }
}

Then you will be able to deserialize with JsonConvert.DeserializeObject<Response>().

The EmbeddedJsonConverter class extracts the json string from the object and then deserializes it. CanConvert should probably be made smarter for a truly generic use.



来源:https://stackoverflow.com/questions/48449441/how-do-i-deserialize-a-property-containing-an-escaped-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!