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

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));

Related

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

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.

Having error upon trying to parse a JSON array into JSON object

I am trying to parse a JSON array by using this code:
public async Task QuoteAsync()
{
await this.Context.Channel.TriggerTypingAsync();
var client = new HttpClient();
var result = await client.GetStringAsync("https://zenquotes.io/api/random");
JArray qarray = JArray.Parse(result);
JObject quote = JObject.Parse(qarray[0]["q"].ToString());
JObject author = JObject.Parse(qarray[0]["a"].ToString());
await this.ReplyAsync($"{quote} - {author}");
}
The response I receive upon sending a request to zenquotes api is
[
{
"q": "Be where your enemy is not.",
"a": "Sun Tzu",
"h": "<blockquote>“Be where your enemy is not.” — <footer>Sun Tzu</footer></blockquote>"
}
]
I can't seem to figure out why the error is occurring since I don't really see any issues.
This is the error I am getting:
Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
The error is occurring on the 7th line:
JObject quote = JObject.Parse(qarray[0]["q"].ToString());
and since the 8th line is the same I expect the same error.
According to JObject.Parse,
Load a JObject from a string that contains JSON.
For your "q" and "a", it is just a simple string but not a JSON string. Hence you should not use JObject.Parse.
With .ToString(), it is good enough to retrieve the value of q and a.
string quote = qarray[0]["q"].ToString();
string author = qarray[0]["a"].ToString();
Sample program

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... ");
}

Parsing JSON API in C#

so I'm fairly new to programming but am looking to go much deeper with it. I recently started to get involved in a project to create a WinForm program for a website that uses an API system in JSON.
I've never used an API before so I'm not quite sure how it works but after looking at it for a few minutes I seem to have the gist of it. What I don't get is how exactly parsing JSON in C# works.
I found
this link after a little google searching. And I got it working (somewhat) with this code.
static void Main(string[] args)
{
WebClient c = new WebClient();
var vLogin = c.DownloadString("https://www.openraid.us/index.php/api/login/username/password");
//Returns string
//{"status":1,"error":null,"token":"250-1336515541-c48d354d96e06d488d1a2530071ef07c9532da26"}
//Token = random, no decisive length*/
JObject o = JObject.Parse(vLogin);
Console.WriteLine("Login Status: " + o["status"]);
String sToken = "" + o["token"];
Console.WriteLine(sToken);
Console.WriteLine("");
//Breaks after this
var myRaids = c.DownloadString("https://www.openraid.us/index.php/api/myraids/"+sToken);
JObject r = JObject.Parse(myRaids); //error occurs here
String sEventId = "" + r["event_id"];
Console.WriteLine("Event ID: " + sEventId);
Console.ReadLine();
}
So to me it looks like I have parsing 1 page done and handled, but when I move onto the second I get this error.
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
So I guess my question is, how do I parse more than 1 page or call of JSON and what would be the easiest way to break up each section of the JSON object (Such as status, error, and token, into C# strings?
Did you try to JArray instead? Depending on what kind of object you are trying to return
WebClient client = new WebClient();
var data = client.DownloadString("");
var jArray = JArray.Parse(data);
JSON requires brackets for arrays and commas between multiple objects.
This is per the JSON standard. I also recommend using JSON.net via NuGet instead of the native JSON parser unless it is overkill and you cannot have the extra bloat.
For example, your parsing a file with two seperate JSON objects - the following does not work per the JSON standard (lacks a comma between the 2 objects and the two objects are not encapsulated by brackets):
{"status":1,"error":null}
{"status":2,"error":null}
The following 3 JSON objects parsed from a file does work (has brackets for multiple objects and commas between objects):
[{"glossary": {"title": "fun glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "grey glossary","SeeAlso": ["GML", "XML"]},
{"glossary": {"title": "blue glossary","SeeAlso": ["GML", "XML"]}]
You can cut every JSON object(Array) into more object using for loops
the C# API is System.Json
var jsonArray = JsonArray.Parse(st);//st is the string which contain the JSON objects
foreach (var item in jsonArray) {
JsonObject ob = new JsonObject(item);
foreach (var t in ob.Values) {
JsonObject oo = new JsonObject(t);
foreach (var x in oo) {
textBox1.AppendText(x.Key + “ : ” + x.Value + “\n”);
}
}
}

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