JSON.parse throws Unexpected token - json

why would this string throw error in JSON.parse
[{"name":"listName","readonly":false,"value":"list"},{"name":"showHeader","readonly":true,"value":false},{"name":"showBorder","readonly":true,"value":false},{"name":"transparent","readonly":true,"value":true},{"name":"showTitle","readonly":false,"value":false},{"name":"showDesc","readonly":false,"value":false},{"name":"showMods","readonly":false,"value":false},{"name":"showTools","readonly":false,"value":true}]
This is the code. the above string is returned via AJAX as widgetInstance.data
if ($scope.widgetInstance.widgetId == 6)
{
$scope.widgetData = JSON.parse($scope.widgetInstance.data);
} else {
$scope.widgetData = JSON.parse($scope.widgetInstance.dataSanitized);
}

I had the same problem once in java while I tried to parse a json object decrypted with an RSA key. Because of the padding, the decrpytion had result in many trailing "\0" at the end of the string. This leads to the json parser error. Perhaps you are in the same trouble?

Related

JSON decoding from stream in Kotlin

I have a server set up to send messages over a local host port. I am trying to decode the serialized json messages sent by the server and get this error.
Error decoding message: kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 55: Expected EOF after parsing, but had instead at path: $
JSON input: .....mber":13,"Timestamp":5769784} .....
The Racer State messages are formatted in JSON as follows: { “SensorId”: “value”, “RacerBibNumber” : “value”, “Timestamp” : “value” }, where the value’s are character string representations of the field values. I have also tried changing my RacerStatus Class to take String instead of Int but to a similar error. Am I missing something here? The symbol that is missing in the error was not able to be copied over so I know it's not UTF-8.
I have also added
val inputString = bytes.toString(Charsets.UTF_8)
println("Received input: $inputString")
This gets
Received input: {"SensorId":0,"RacerBibNumber":5254,"Timestamp":3000203}
with a bunch of extraneous symbols at the end.
data class RacerStatus(
var SensorId: Int,
var RacerBibNumber: Int,
var Timestamp: Int
) {
fun encode(): ByteArray {
return Json.encodeToString(serializer(), this).toByteArray()
}
companion object {
fun decode(bytes: ByteArray): RacerStatus {
print(bytes[0])
try {
val mstream = ByteArrayInputStream(bytes)
return Json.decodeFromStream<RacerStatus>(mstream)
} catch (e: SerializationException) {
println("Error decoding message: $e")
return RacerStatus(0, 0, 0)
}
// return Json.decodeFromString(serializer(), mstream.readBytes().toString())
}
}
}
So I found an answer to my question. I added a regex to include just the json components I know my json contains.
val str = bytes.toString(Charsets.UTF_8)
val re = Regex("[^A-Za-z0-9{}:,\"\"]")
return Json.decodeFromString<RacerStatus>(re.replace(str,""))
I thought that Charsets.UTF_8 would remove the misc characters but it did not. Is there a more intiuative solution? Also is there a regex that would cover all possible values in json?

Volley response JSON Exception: Unterminated array at character

I use Volley to get data from Xtream server.
It normally works, but when it sends certain requests, Volley returns an unterminated array which occurs a JSONException.
I had some investigation on it, and found that those cases are when the server returns relatively large amount of data, and that the response string emits some symbols such as comma, bracket etc.
try {
...
JSONArray array = new JSONArray(data);
...
} catch(JSONException e) {}
How can I pretreat the variable "data" so the above statement won't return any Exception?
Thank you for your reply in advance.

Handling Byte Order Mark (BOM) character in Json.NET

For a .NET Core project, I'm consuming a public API that returns data formatted as JSON. However, some (not all) of their responses have a BOM character at the start of the string, which causes Visual Studio and Json.NET to not recognize the string as valid JSON. As a result, I get an error when using JsonConvert.DeserializeObject() to deserialize the string into my POCO object. I've been told by the API developers that the BOM is included by design, and that I should "set Json.Net to expect that". Is there a way to set Json.NET to handle the BOM without stripping it off the string manually?
Example follows, by request. You can see when the API GET completes successfully, I'm having to trim the BOM manually from the start of the string, otherwise the call to DeserializeObject() fails because the string is not valid JSON.
private static MyPOCO GetObjectFromApi(string url)
{
MyPOCO poco = new MyPOCO();
RestClient client = new RestClient(url);
RestRequest request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
poco = JsonConvert.DeserializeObject<MyPOCO>(response.Content.TrimStart((char)65279)); // trim the byte order marker character at the start of the string
//poco = JsonConvert.DeserializeObject<MyPOCO>(response.Content); // this would throw an error because response.Content is not valid JSON
}
else
{
MyLogger.WriteLog("Api returned failure response");
}
return poco;
}

JSONParser.parse() error

I have been getting a error parse my JSON file
Input
{"continent":"South America","recentJobRank":717,"latitude":"-34.6037232","lastSeenDate":"2012-11-23","start":"Inmediato","contactPerson":"Alejandra Perez","lastJobRank":2,"title":"Encimador","salary":"Convenio","jobtype":"Tiempo Completo","url":"http://www.computrabajo.com.ar/bt-ofrd-deglay-7148.htm","postedDate":"2012-11-21","duration":"Indeterminada","firstSeenDate":"2012-11-23","phoneNumber":"011 4648-0226 RRHH","faxNumber":"011 4648-0226","location":"Buenos Aires, Argentina","company":"Deglay S.R.L.","id":"34076","department":"Buenos Aires","category":"others","applications":"Por e-mail o comunicandose a los telefonos","longitude":"-58.3815931"}
Below is the exception i have recieved
Exception
Unexpected character (J) at position 457.
Exception Caught in addfields
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
I have tried checking my json on a Validator.It seems fine.
Any obvious mistake that i am making ?
The JSON is definitely correct, since JSON.parse() accepts it.
I can't really reproduce your error with the json-simple library. I downloaded every version available here, copy-pasted your JSON string and passed it to JSONParser.parse() and got no error in any version.
Here is my setup:
public static void main(String[] args) {
try {
StringReader x = new StringReader("{\"continent\":\"South America\",\"recentJobRank\":717,\"latitude\":\"-34.6037232\",\"lastSeenDate\":\"2012-11-23\",\"start\":\"Inmediato\",\"contactPerson\":\"Alejandra Perez\",\"lastJobRank\":2,\"title\":\"Encimador\",\"salary\":\"Convenio\",\"jobtype\":\"Tiempo Completo\",\"url\":\"http://www.computrabajo.com.ar/bt-ofrd-deglay-7148.htm\",\"postedDate\":\"2012-11-21\",\"duration\":\"Indeterminada\",\"firstSeenDate\":\"2012-11-23\",\"phoneNumber\":\"011 4648-0226 RRHH\",\"faxNumber\":\"011 4648-0226\",\"location\":\"Buenos Aires, Argentina\",\"company\":\"Deglay S.R.L.\",\"id\":\"34076\",\"department\":\"Buenos Aires\",\"category\":\"others\",\"applications\":\"Por e-mail o comunicandose a los telefonos\",\"longitude\":\"-58.3815931\"}");
new JSONParser().parse(x);
} catch(Exception e) {
System.out.println("Error: " + e);
}
System.out.println("Success");
}
So I assume neither your JSON, nor the library is at fault here. My guess would be the encoding of your JSON string, since the error message says
Unexpected character (J) at position 457.
and there is no J anywhere close to this position. So either the JSON you receive is encoded in a way, which SimpleJSON can't correctly parse, or the data doesn't get transmitted completely/correctly.
Maybe it could help to tell, where you got the JSON from and how you pass it into JSONParser.parse().

JSON accepted format according to Newtonsoft Json

I am trying to parse some JSON objects which is made just of (string,string) pairs, in order to emulate Resjson behaviour. The file I am parsing contains this.
{
"greeting":"Hello world",
"_greeting.comment":"Hello comment.",
"_greeting.source":"Original Hello",
}
Please note the last comma is incorrect, and I also used http://jsonlint.com/ to test JSON syntax. It tells me it is incorrect, as I expected. My - slightly modified - code is :
string path = #"d:\resjson\example.resjson";
string jsonText = File.ReadAllText(path);
IDictionary<string, string> dict;
try
{
dict = JsonConvert.DeserializeObject<IDictionary<string, string>>(jsonText);
}
catch(Exception ex)
{
// code never reaches here
}
My above code returns the IDictionary with the 3 keys as if the formatting was correct. If I serialize back, the string obtained is without the last comma.
My questions are :
Is Newtonsoft.Json so permissive that it allows users slight errors ?
If so, can I set the permissiveness so that it is more strict ?
Is there a way to check if a string is valid JSON format, using
Newtonsoft.Json with and/or without the permissiveness?