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().
Related
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.
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?
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 ?
I am writing junit test cases in play. I want to read certain configurations from a configuration file. So I am loading that file programatically
private Configuration additionalConfigurations;
Config additionalConfig = ConfigFactory.parseFile(new File("conf/application.conf"));
Config resolConfig = additionalConfig.resolve(ConfigResolveOptions.noSystem());
additionalConfigurations = new Configuration(scaleBasedConf);
running(fakeApplication(additionalConfigurations.asMap()), new Runnable() {
public void run() {
// test Code
}
While running my test case using "play test" I am getting error "Token not allowed in path expression: '[' (you can double-quote this token if you really want it here)
" . My configuration where I am getting this error is
Mykey.a.b.c"[]".xyz = "value"
I have double quoted square brackets. But still getting the error.
After hours of research I finally found out the reason why this is throwing exception. It is because when I do
Config additionalConfig = ConfigFactory.parseFile(new File("conf/application.conf"))
additionalConfig.resolve(ConfigResolveOptions.noSystem());
Then it parses the configuration file taking double quotes in consideration and thus dont give any exception. However it does 1 more thing, it removes those double quotes while parsing. Then the map which we get after parsing , we are passing it to
fakeApplication(additionalConfigurations.asMap()
have key like -> Mykey.a.b.c[].xyz
Here, what play does it again parses the map . Now when double quotes are removed, it throws exception . So the solution for it is-
Mykey."\""a.b.c"[]"\"".xyz = "value"
Doing this, in first parse it creates string as - > Mykey."a.b.c[]".xyz and so in second parse it goes well and dont throw any exception.
I am attempting to build a REST service using Netty on the backend. I need to be able to post raw JSON to the service outside of any key/value parameters. Content-type=applicaiton/json not form multi-part.
I am able to get the initial part of the service to receive the request, but when I cast the MessageEvent content to HTTPRequest, it no longer has any posed data associated with it. That leaves me with no ability to get the JSON data back.
In order to access the posted JSON, do I need to use a different process for extracting the data from the MessageEvent?
Here is the snippet in question.
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
System.out.println("The message was received");
HttpRequest request = (HttpRequest) e.getMessage();
if (request.getMethod() != POST) {
sendError(ctx, METHOD_NOT_ALLOWED);
return;
}
// Validate that we have the correct URI and if so, then parse the incoming data.
final String path = sanitizeUri(request.getUri());
decoder = new HttpPostRequestDecoder(request);
System.out.println("We have the decoder for the request");
List<InterfaceHttpData> datas = decoder.getBodyHttpDatas();
for (InterfaceHttpData data : datas){
System.out.println(data.toString());
}
What am I missing that it causing this? Do I need to use the ChunkedWrite portion? I am a noob to Netty so forgive me if this is basic. I found lots of other questions about posting raw JSON to other URL's from inside Netty, but nothing about receiving it.
I've only used HttpPostRequestDecoder to read application/x-www-form-urlencoded or mime data.
Try just reading the data directly form the request as per the snoop example.
ChannelBuffer content = request.getContent();
if (content.readable()) {
String json = content.toString(CharsetUtil.UTF_8);
}