0

I have a JSON structure like the following:

{
    "totalCount": 2,
    "entries": [
        {
            "id": "80e88220-af3c-11e8-a8d1-02faede05ee2",
            "logType": "Success",
            "dateCreated": "2018-09-03T05:45:14",
            "message": "{\"orderType\":\"Report\",\"language\":\"en\",\"payloadSize\":45439}"
        },
        {
            "id": "a8130f00-af3c-11e8-a8d1-02faede05ee2",
            "logType": "Success",
            "dateCreated": "2018-09-03T05:46:14",
            "message": "{\"orderType\":\"Report\",\"language\":\"en\",\"payloadSize\":45439}"
        }
}

I am trying to deserialize this into the following classes:

public class ApiResponse
{
    public int TotalCount { get; set; }
    public List<Entry> Entries { get; set; }
}

public class Entry
{
    public string Id { get; set; }
    public string LogType { get; set; }
    public DateTime DateCreated { get; set; }
    public Message Message { get; set; }
}

public class Message
{
    public string OrderType { get; set; }
    public string Language { get; set; }
    public int PayloadSize { get; set; }
}

I am using Json.NET to deserialize the object to the classes. I had hoped that it could dynamically see the string and try to parse it into the Message class but it hasn't been working.

var logs = JsonConvert.DeserializeObject<ApiResponse>(responseContent);

This causes a JsonSerializationException

Error converting value "{"orderType":"Report","language":"en","payloadSize":45439}" to type 'ConnectApiUsage.Message'. Path 'entries[0].message', line 8, position 84.

Could not cast or convert from System.String to ConnectApiUsage.Message.

Is this type of deserialization not possible or am I just missing an attribute? I tried looking through the Json.NET documentation but couldn't find anything for this specific case. I know I can just put it into a string and deserialize this field later, but I was hoping to do it all in one step.

Evan Frisch
  • 1,334
  • 5
  • 22
  • 40
  • Your json is double encoded. So `message:` isn't valid json anymore. Your fix should be to find out what is double encoding your json and fix that – Liam Sep 12 '18 at 16:09
  • Try adding the "[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]" attribute to the message and entry classes and adding the type info to the json – James Morrison Sep 12 '18 at 16:09
  • @Liam I know that the message is encoded as a string. I can't control the source so I was trying to deserialize that with the outer object. – Evan Frisch Sep 12 '18 at 16:11
  • Check out https://stackoverflow.com/questions/49454071/model-binding-json-data-with-metadatapropertyhandling-in-asp-net-mvc-core-2 - should be the same principle – James Morrison Sep 12 '18 at 16:11

0 Answers0