简体   繁体   中英

C# Json deserialization error

I want to convert json string to C# datatable and my json string contains another json string. I don't want to convert internal json string (keep it as string only). this is my code

 string js = "[{\"FirstName\":\"first\",\"LastName\":\"second\",\"jsonStr\":\"[{\"abc\":\"a\",\"xyz\":\"x\"}]\"}]";
            DataTable dt = (DataTable)JsonConvert.DeserializeObject(js, (typeof(DataTable)));
            gv.DataSource = dt;
            gv.DataBind();

But I am getting an error

After parsing a value an unexpected character was encountered: a. Path '[0].jsonStr', line 1, position 56.

Your JSON is invalid. After unescaping, it becomes the following string:

[
    {
        "FirstName" : "first",
        "LastName" : "second",
        "jsonStr" : "[{" abc ":" a "," xyz ":" x "}]"
    }
]

Stack Overflow syntax highlighting suggests that your JSON is invalid.
You can also check the JSON validity here .

In order to make it valid, your quotes within jsonStr should have been escaped again:

string js = "[{\"FirstName\":\"first\",\"LastName\":\"second\",\"jsonStr\":\"[{\\\"abc\\\":\\\"a\\\",\\\"xyz\\\":\\\"x\\\"}]\"}]";

This C# string now contains the following JSON, which is valid:

[
    {
        "FirstName": "first",
        "LastName": "second",
        "jsonStr": "[{\"abc\":\"a\",\"xyz\":\"x\"}]"
    }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM