Nevi Nevi - 6 days ago 8
JSON Question

Unexpected character encountered while parsing JSON string

Any idea what could be wrong with this JSON string?

"\"iccid\":\"8500000000000000005\",\"msisdn\":\"4485000000005\",\"comment\":null,\"lastSessionStart\":1480120318000,\"lastSessionEnd\":1480120456000,\"simStatus\":\"Live\",\"activated\":true,\"enabled\":true,\"connected\":false,\"usage\":73728}"


I tried unescaping it by:

json = json.Replace("\\\"", "");


but I'm still getting this error:


Unexpected character encountered while parsing value: 1. Path
'lastSessionStart', line 1, position 91.


JSONLint.com says it's a valid JSON format.

Answer

If this is your actual JSON string, it looks like it is double-serialized. To get the data out, you'll need to deserialize it twice: once the get the unescaped JSON, and once to get the actual data.

Using json = json.Replace("\\\"", ""); to try to unescape the string will not work properly-- that will actually remove the all the quotes in addition to the backslashes, making the JSON invalid.

Try like this instead, where json is the string in your question:

string unescapedJson = JsonConvert.DeserializeObject<string>(json);
Data data = JsonConvert.DeserializeObject<Data>(unescapedJson);

and Data is the following class:

public class Data
{
    public string iccid { get; set; }
    public string msisdn { get; set; }
    public string comment { get; set; }
    public long lastSessionStart { get; set; }
    public long lastSessionEnd { get; set; }
    public string simStatus { get; set; }
    public bool activated { get; set; }
    public bool enabled { get; set; }
    public bool connected { get; set; }
    public int usage { get; set; }
}

Fiddle: https://dotnetfiddle.net/DOiSUx

Comments