C# How to get rid of "\" from JSON? - c#

I have following C# code which generates output like this:
Task<OnlineResponse> task = client.Execute(query);
OnlineResponse response = task.Result;
Result result = response.Results[0];
dynamic resultJson = JsonConvert.SerializeObject(result.Data);
var x = Regex.Replace(resultJson.ToString(), #"[\[\]']+", "");
return x;
This is output:
"{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756289-919567--
accrual\",\"BATCH_DATE\":\"02/01/2022\"}},
{\"GLDETAIL\":{\"RECORDNO\":\"264378-1756290-919568--
accrual\",\"BATCH_DATE\":\"02/01/2022\"}}"
I am trying to get rid of all backslashes.
I applied "Regex.Replace", but it would not work.
This is expected output:
"{"GLDETAIL":{"RECORDNO":"264378-1756289-919567--
accrual","BATCH_DATE":"02/01/2022"}},
{"GLDETAIL":{"RECORDNO":"264378-1756290-919568--
accrual","BATCH_DATE":"02/01/2022"}}"

you serialized json string twice. just return the result.Data as it is. its already a json string. if you remove backslashes you wont be able deserilze the object.

Related

Unexpected character encountered while parsing value: j. Path '', line 0, position 0

t fails to deserialize/prase this json, ive tried multiple combinations with different methods to try and make this work but nothing seems to do it...
The code im using
WebClient wc = new WebClient();
var json = (JObject)JsonConvert.DeserializeObject(wc.DownloadString("http://services.runescape.com/m=website-data/playerDetails.ws?names=[%22" + Username.Replace(" ", "%20") + "%22]&callback=jQuery000000000000000_0000000000&_=0"));
the json its trying to deserialize...
jQuery000000000000000_0000000000([{"isSuffix":true,"recruiting":false,"name":"Sudo Bash","clan":"Linux Overlord","title":"the Troublesome"}]);
In Json specification you can see that [ indicates the begining array of json objects while { indicates beginning of new json object.
Your json string starts with [ so it can contains more json objects ( because it's an array and it contains jQuery000000000000000_0000000000( which is your query string parameter. To get rid of the query string garbage you should find out the scheme of that garbage and then to process json object I would recommend you to deserialize your json string into List<JObject> using JsonConvert.DeserializeObject<T>() method if your json string starts with [ ( use standard type if it is starting with { );
Example :
string url = // url from #Darin Dimitrov answer
string response = wc.DownloadString(url);
// getting rid of the garbage
response = response.Substring(response.IndexOf('(') + 1);
response = response.Substring(0, response.Length - 1);
// should get rid of "jQuery000000000000000_0000000000(" and last occurence of ")"
JObject result = null;
if(response.StartsWith('['))
{
result = JsonConvert.DeserializeObject<List<JObject>>(response)[0];
}
else
{
result = JsonConvert.DeserializeObject<JObject>(response);
}
What you are trying to deserialize is not JSON but rather JSONP (which is JSON wrapped in a function call).
Remove this parameter from your query string:
&callback=jQuery000000000000000_0000000000
and you should be good to go with a properly formatted JSON:
var url = "http://services.runescape.com/m=website-data/playerDetails.ws?names=[%22" + Username.Replace(" ", "%20") + "%22]&_=0";
var json = (JObject)JsonConvert.DeserializeObject(wc.DownloadString(url));

WebRequest returning JSON but with lots of /n/t

Hey all I currently am getting this response back from when I am calling a API call to get user information:
This is AFTER it try's to do the takeOutSpaces function which looks like this:
public string takeOutSpaces(string data)
{
string result = data;
char cr = (char)13;
char lf = (char)10;
char tab = (char)9;
result = result.Replace("\\r", cr.ToString());
result = result.Replace("\\n", lf.ToString());
result = result.Replace("\\t", tab.ToString());
return result;
}
So I'm not sure how to go about using something else to try to get rid of all those /n and /t's.
Your takeOutSpaces is looking for actual instances of \r etc. (which would appear as \\r in debug view) and replacing it with a carriage return (which would appear as \r in the debug view).
To remove those spaces you want to actually replace the whitespace, though it's probably not worth doing since it's more readable (outside of debug view) with it in, and any JSON parser should be fine with it.
Modifying the takeOutSpaces function make it work:
public string takeOutSpaces(string data)
{
string result = data;
result = result.Replace("\r", "");
result = result.Replace("\n", "");
result = result.Replace("\t", "");
return result;
}

How to parse JSON while using variables?

I am parsing JSON using C#
This code works fine:
var json = webClient.DownloadString("API KEY");
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json);
Console.WriteLine(DefindexS);
price = (double)o["response"]["prices"]["5021"]["6"]["0"]["current"]["value"];
currency = (string)o["response"]["prices"]["5021"]["6"]["0"]["current"]["currency"];
Console.WriteLine("price" + price);
Console.WriteLine("Currency" + currency);
It prints correctly
price7.11
Currencymetal
here is the catch. The "5021" in both the cases above needs to be replaced by a variable which is set by the user. The JSON data is alright. as long as the number is correct, it will return a proper value.
The variable is DefindexS. I tried parsing by replacing "5021" by DefindexS (I have set the value to 5021) but it gave me an Unhandled Exception error.
Then I tried to format it and did this:
string realdef = String.Format("\"{0}\"", DefindexS.ToString());
Console.WriteLine(realdef);
var json = webClient.DownloadString("API KEY");
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(json);
price = (double)o["response"]["prices"][realdef]["6"]["0"]["current"]["value"];
currency = (string)o["response"]["prices"][realdef]["6"]["0"]["current"]["currency"];
Console.WriteLine("price" + price);
Console.WriteLine("Currency" + currency);
The outcome:
"5021"
and then it crashes.. realdef prints as "5021" so the formatting happened properly. Why am I still getting an error?
You don't have to add the quotes around your variable. So this line of code is not needed:
string realdef = String.Format("\"{0}\"", DefindexS.ToString());
It should work when you change it to
string realdef = DefindexS.ToString();

Newtonsoft Json.Net correct parsing of string arrays inside a JSON object

I have the following problem, I want to parse a Json object I get passed by a url query string
e.g.
...&json={tags=[tag1,tag2]}
I have used
JsonConvert.DeserializeObject<Dictionary<string, object>>(json)
But when calling the Deserialize method I get an error
Newtonsoft.Json.JsonReaderException : Unexpected character encountered while parsing value: d. Line 1, position 8.
If I pass in the string
"{tags:[\"tag1\",\"tag2\"]}
It works fine, I don't want my users to have to add the "" quotes
Is there a way to work around this problem?
pseudocode For a solution could be...
Grab the json query string element.
Split on first equals "=".
Grab all text between "{tags=[" and "]}"
Take that text split on ","
trim any whitespace off of the items.
Join them back together but put quotes around them and coma delimited them.
put that value back inbetween "{tags=[" and "]}" ie "{tags=[" + newValue+ "]}"
Here is some sample C# code...
[Test]
public void TestHack()
{
string almost = "{tags=[tag1,tag2]}";
string json = this.HackToJson(almost);
Trace.WriteLine(json);
}
public string HackToJson(string almostJson)
{
if( almostJson.StartsWith("{tags=[") && almostJson.EndsWith("]}"))
{
int tagsLen = "{tags=[".Length;
string tags = almostJson.Substring(tagsLen, almostJson.Length - (tagsLen + 2));
var items = tags.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
var itemsCleaned = (from c in items select "\"" + c.Trim() + "\"");
var jsonpart = string.Join(",", itemsCleaned);
var json = string.Format("{{tags=[{0}]}}", jsonpart);
return json;
}
throw new NotImplementedException("not sure what to do here... ");
}

Json.NET: Deserilization with Double Quotes

I am trying to deserialize a json string received as a response from the service. The client is Windows Phone 7, in C#. I am using Json .NET - James Newton-King deserializor to directly convert the Json string to objects. But sometimes the Json string contains some comments information with double quotes (") in them and the deserializer fails and throws an error. Looks like this is an invalid Json string according to Jsonlint.
{
"Name": "A1",
"Description": "description of the "object" A1"
}
How to handle such Json String. If it is (\"), then it works. But I cannot replace all (") with (\") as there might be double quotes in other part of the json string. Is there any decode function of Json .Net?
It looks like HttpUtility.JavaScriptStringEncode might solve your issue.
HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(yourObject))
Just do:
yourJsonString = yourJsonString.Replace("\"", "\\u022");
object o = JSonConvert.Deserialize(yourJsonString);
\u022 is the ascii code for double quotes. So replacing quotes for \u022 will be recognized by your browser.
And use \ in "\u022" to make c# recognize backslash character.
Cheers
You can improving this.
static private T CleanJson<T>(string jsonData)
{
var json = jsonData.Replace("\t", "").Replace("\r\n", "");
var loop = true;
do
{
try
{
var m = JsonConvert.DeserializeObject<T>(json);
loop = false;
}
catch (JsonReaderException ex)
{
var position = ex.LinePosition;
var invalidChar = json.Substring(position - 2, 2);
invalidChar = invalidChar.Replace("\"", "'");
json = $"{json.Substring(0, position -1)}{invalidChar}{json.Substring(position)}";
}
} while (loop);
return JsonConvert.DeserializeObject<T>(json);
}
Example;
var item = CleanJson<ModelItem>(jsonString);
I had the same problem and i found a possible solution. The idea is to catch the JsonReaderException. This exception bring to you the attribute "LinePosition". You can replace this position to an empty character (' '). And then, you use this method recursively until whole json is fixed.
This is my example:
private JToken processJsonString(string data, int failPosition)
{
string json = "";
var doubleQuote = "\"";
try
{
var jsonChars = data.ToCharArray();
if (jsonChars[failPosition - 1].ToString().Equals(doubleQuote))
{
jsonChars[failPosition - 1] = ' ';
}
json = new string(jsonChars);
return JToken.Parse(json);
}
catch(JsonReaderException jsonException)
{
return this.processJsonString(json, jsonException.LinePosition);
}
}
I hope you enjoy it.
I would recommend to write email to server admin/webmaster and to ask them fix this issue with json.
But if this is impossible, you can write simple parse that finds nonescaped doublequotes inside doublequotes and escapes them. It will hardly be >20lines of code.
you can use newtonsoft library to convert it to object( to replace \" with "):
dynamic o = JObject.Parse(jsondata);
return Json(o);

Categories

Resources