-1

I am getting the following exception when trying to deserialize a json object:

JsonSerializationException: Error converting value "[{"ID":"1111","FirstName":".","LastName":"test","AdditionalName":"","ID_PassportNum":"NONE","DateOfBirth":""}] to type 'System.Collections.Generic.List`1[MoblieCP.Models.UserInfo]'. Path 'Data', line 1, position 1303

I'm getting responses from the server in the following format:

{
"CodeError":0,
"Data":"[{\"ID\":\"1111\",\"FirstName\":\".\",\"LastName\":\"test\",\"AdditionalName\":\"\",\"ID_PassportNum\":\"NONE\",\"DateOfBirth\":\"\"}]",
"ErrorMessage":null
}

the Data part is always a list, even if it has one item.

I built a generic class which holds server responses:

public class GenericResponse<T>
{
    [JsonProperty("CodeError")]
    public ResponseCodes CodeError { get; set; }

    [JsonProperty("Data")]
    public T Data { get; set; }

    [JsonProperty("ErrorMessage")]
    public string ErrorMessage { get; set; }
}

This is the part where im trying to deserialize:

jsonResult = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
var json = JsonConvert.DeserializeObject<GenericResponse<List<UserInfo>>(jsonResult);

Every time JsonConverter returns that exception.

When I try to deserialize "data" on its own (not as part of the GenericResponse object) into List<UserInfo>, I succeed. But I don't want to have to do 2 deserializations every time.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Could you please show the `UserInfo` class? – er-sho Oct 13 '19 at 05:51
  • 3
    Your problem is that `Data` is embedded double-serialized JSON. I.e. on the server side somebody serialized the value of `Data` to a JSON string, embedded it in the outer response object as a string value, then serialized the response object itself to JSON. To get around this, you can apply `EmbeddedLiteralConverter>` from [this answer](https://stackoverflow.com/a/39154630/3744182) to [How do I convert an escaped JSON string within a JSON object?](https://stackoverflow.com/q/39154043/3744182). In fact this seems to be a duplicate, agree? – dbc Oct 13 '19 at 07:07

1 Answers1

3

It seems when the data was serialized, firstly List<UserInfo> serialized, then it added to the whole object. That's why you have to deserialize it 2 times.

Nabi Sobhi
  • 369
  • 4
  • 16
  • Thank you so much! I have checked the back end code, and indeed Data was serialized and then added to the result object to be serialized again. – Dima Shmushkin Oct 13 '19 at 07:11