SVI
SVI

Reputation: 1651

Error while using Newtonsoft.Json to parse a Json string

My JSON string looks like this. Please note that it has escape characters.

string json = "\"{\\\"Status\\\":true,\\\"ID\\\":24501}\"";

When I use the Parse method like below I run into an error stated below:

JObject o = JObject.Parse(json);

Error reading JObject from JsonReader. Current JsonReader item is not an object: String

How do I get rid of this error or is there any other method to parse my json string and fetch the values?

Upvotes: 8

Views: 9910

Answers (6)

Milen
Milen

Reputation: 8877

Had similar issue today. My solution to this is contained in this extension method (using c#):

public static class StringExtensions
{
    public static string RemoveDoubleEncoding(this string text)
    {
        if(string.IsNullOrEmpty(text))
            return string.Empty;
        var result = text.TrimStart('\"').TrimEnd('\"');
        result = result.Replace(@"\", string.Empty);
        return result;
    }
}

Upvotes: 0

GP24
GP24

Reputation: 877

As SolarBear says in his comment, the problem is double-escaping.

To get the proper format, like this:

string json = "{\"Status\":true,\"ID\":24501}";

Do something like this:

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

Upvotes: 0

Samuel
Samuel

Reputation: 303

You need something like this

json = json.Replace(@"\", string.Empty).Trim(new char[]{'\"'})

Upvotes: 1

DevT
DevT

Reputation: 4933

in here format should be something like this:

string jsonNew = @"{'Status': True,'ID': 24501 }";

Upvotes: 0

Joe
Joe

Reputation: 82654

It seems like your object is double encoded. Try:

string json = "{\"Status\":true,\"ID\":24501}";

Upvotes: 2

MByD
MByD

Reputation: 137442

Remove first and last quotes:

string json = "{\"Status\":true,\"ID\":24501}";

See the Json format here.

Upvotes: 4

Related Questions