如何反序列化包含转义的JSON字符串的属性?

时间:2018-01-25 18:17:57

标签: c# json.net

我从API获得application/json响应,该API具有属性,其本身包含转义的JSON字符串。

{
    "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"
  }

我想将对象和内部对象反序列化为模型类型。

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

使用这样的电话

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

但是,Netwonsoft.Json正好处理外部属性,但在匹配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 个答案:

答案 0 :(得分:2)

您可以使用自定义JsonConverter,类似于此:

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

使用[JsonConverter(typeof(EmbeddedJsonConverter))]标记属性,如:

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

然后,您将能够使用JsonConvert.DeserializeObject<Response>()反序列化。

EmbeddedJsonConverter类从对象中提取json字符串,然后对其进行反序列化。 CanConvert应该更加智能化,以实现真正的通用用途。