Volley response JSON Exception: Unterminated array at character - json

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.

Related

Calling an API returns expected JSONArray, found JSONObject

I'm calling an API from Go and trying to push json string data from another api call into it.
I can hand craft the calls using a payload like
payload := strings.NewReader('[{"value1":333, "value2":444}]'
and everything is happy.
I'm now trying to covert this to take the json string {"value1":333, "value2":444} as an input parameter of type string to a function, but when I try and use that as the payload, the api is responding with
expected type: JSONArray, found: JSONObject
I naively tried setting the input to the function as []string and appending the data to an array as the input, but then strings.NewReader complained that it was being fed an array.. which is was.
I'm at a loss to work out how to convert a string of json into a json array that the api will be happy with.
I tried just surrounding the string with [] but the compiler threw a fit about incorrect line termination.
Must have been doing something wrong with the string, surrounding the {} with [] let the function pass the data, but there must be a better way than this.
Any ideas, or am I making this harder than it should be?
You were on the right track with the brackets, but you actually need to append the characters to the string. For example:
str := `{"value1":333, "value2":444}`
str = "[" + str + "]"
// [{"value1":333, "value2":444}]
https://play.golang.org/p/rWHCLDCAngd
If you use brackets outside a string or rune literal, then it is parsed as Go language syntax.

How to convert compact Json to pretty print codename one

I want to know how to convert a string of compact Json to pretty print so that I can parse it. I have searched for this question in stack overflow but it doesn't seem like anyone has asked it for codename one.
Right now I have a string of compact Json but it can not be parsed. This is the code:
String JsonData = "{\"document\":{ \"type\":\"PLAIN_TEXT\", \"content\":\"Ask not what your country can do for you, ask what you can do for your country.\" },\"encodingType\":\"UTF8\"}";
JsonResponse = Rest.
post("https://language.googleapis.com/v1/documents:analyzeSyntax?key=[API KEY").
jsonContent().
body(JsonData).
getAsJsonMap();
String JsonString = (JsonResponse.getResponseData()).toString();
JSONParser parser = new JSONParser();
Map<String, Object> results = null;
try {
results = parser.parseJSON(new StringReader(JsonString));
} catch (IOException e) {
e.printStackTrace();
System.out.println("fail");
}
System.out.println("results "+results);
But when I run this code I get a bunch of these responses:
[EDT] 0:0:3,269 - Expected null for key value while parsing JSON token at row: 1 column: 5 buffer: e
and
java.lang.NumberFormatException: For input string: "ee0"
How should I convert my string of compact Json (JsonString) to pretty print so that I can parse it? Alternatively, is there a way to directly parse the response (JsonResponse)?
Thank You
You are printing out a map not a JSON string as the JSON data is already parsed. If you just want to look at the network protocol for debugging the best way to do that is open the Network Monitor in the simulator where you will see all HTTP requests and can copy out the response body JSON.
However you can still convert a Map back to JSON using:
Log.p("results " + JSONParser.mapToJson(results));
Notice you should use Log.p() and Log.e() to log strings/exceptions as that would work better on the devices.

JSON.parse throws Unexpected token

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?

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().

How to add input to parsing exceptions in json4s?

Suppose I am parsing JSON with json4s.
val jv = org.json4s.native.JsonMethods.parse(json) // json is any JsonInput
The parse may raise exceptions. Unfortunately those exceptions don't contain the input (json) and sometimes I cannot understand and reproduce them.
I can wrap the parse with a wrapper (see below) but it doesn't work
try org.json4s.native.JsonMethods.parse(json) catch {
case e: Exception => throw new MyParseException(json, e)
}
Now what if json is an InputStream ? Should I read the stream ? What if the JSON is very large ? I probably don't need the whole stream. I need just the part of it up to the character where the parse failed.
How would you suggest add the input to the parsing exceptions ?