Spring MVC can not fetch JSON value - java

In Spring mvc I have a mytable.json file.
I want to fetch that json file data and then want to add to model.addAttribute().
mytable.json
{"name1":["place1.1","place1.2"],
"name2":["place2.1","place1.2"]
...........
.........}
I want to fetch the names with their corresponding citylist.
Ex:
name1=place1.1,place1.2
so,I have done:--
try {
JSONParser parser = new JSONParser();
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/mytable.json").getFile());
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));
Iterator<String> keys = obj.values().iterator();
while( keys.hasNext() )
{
String key = (String)keys.next();
if ( obj.get(key) instanceof JSONObject )
{
model.addAttribute("key", key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
But I am getting error:
Unexpected character (�) at position 0.
in this line :
JSONObject obj = (JSONObject) parser.parse(new FileReader(file));
why??Where is the problem?

The JSONParser parser = new JSONParser(); is expecting a JSON String, not a .json file. hence the Unexpected character.... error.
You can InputStreamReader:
jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("file/mytable.json")));

Related

Java : Not Able to cast jsonobject to Json array

I was able to pull data from an api using my get request method
{"vulnerabilities":[{"id":5027994,"status":"open","closed_at":null,"created_at":"2019-06-07T06:10:15Z","due_date":null,"notes":null,"port":[],"priority":null,"identifiers":["adobe-reader-apsb09-15-cve-2009-2990"],"last_seen_time":"2019-07-24T05:00:00.000Z","fix_id":4953,"scanner_vulnerabilities":[{"port":null,"external_unique_id":"adobe-reader-apsb09-15-cve-2009-2990","open":true}],"asset_id":119920,"connectors":[{"name":"Nexpose Enterprise","id":7,"connector_definition_name":"Nexpose Enterprise","vendor":"R7"}],"service_ticket":null,"urls":{"asset":"dummy.com"},"patch":true,"patch_published_at":"2009-10-08T22:40:52.000Z","cve_id":"CVE-2009-2990","cve_description":"Array index error in Adobe Reader and Acrobat 9.x before 9.2, 8.x before 8.1.7, and possibly 7.x through 7.1.4 might allow attackers to execute arbitrary code via unspecified vectors.","cve_published_at":"2009-10-19T22:30:00.000Z","description":null,"solution":null,"wasc_id":null,"severity":9,"threat":9,"popular_target":false,"active_internet_breach":true,"easily_exploitable":true,"malware_exploitable":true,"predicted_exploitable":false,"custom_fields":[],"first_found_on":"2019-06-05T05:22:23Z","top_priority":true,"risk_meter_score":100,"closed":false}
but in my request method I have received an error in parsing this data , which is that I can not cast an jsonobject to jsonarray.
here is the get request method:
public static void GetRequest() {
BufferedReader reader;
String access_token = "blahblahblah";
String line;
StringBuffer responseContentReader = new StringBuffer();
try {
URL url = new URL("https://api.security.com/vulnerabilities/");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("X-Risk-Token ", access_token);
connection.setRequestProperty("Accept", "application/json");
//here we should be able to "request" our setup
//Here will be the method I will use
connection.setRequestMethod("GET");
//after 5 sec if the connection is not successful time it out
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
//System.out.println(status); //here the connect was established output was 200 (OK)
//here we are dealing with the connection isnt succesful
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContentReader.append(" ");
responseContentReader.append(line);
responseContentReader.append("\n");
}
reader.close();
//returns what is successful
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContentReader.append(" ");
responseContentReader.append(line);
responseContentReader.append("\n");
}
reader.close();
}
JsonParser parser = new JsonParser();
Object object = parser.parse(responseContentReader.toString());
JsonArray array = (JsonArray) object; // here is where the exception occurs
for (int i = 0; i < array.size(); i++) {
JsonArray jsonArray = (JsonArray) array.get(i);
JsonObject jsonobj = (JsonObject) jsonArray.get(i);// cannot cast jsonobject to jsonarray
}
//JsonObject jsonObject = (JsonObject) object;
System.out.println( responseContentReader.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
connection.disconnect();
}
}
here is where the error occurs specifically, I honestly dont know how to go forward with this:
JsonParser parser = new JsonParser();
Object object = parser.parse(responseContentReader.toString());
JsonArray array = (JsonArray) object; // here is where the exception occurs
for (int i = 0; i < array.size(); i++) {
JsonArray jsonArray = (JsonArray) array.get(i);
JsonObject jsonobj = (JsonObject) jsonArray.get(i);// cannot cast jsonobject to jsonarray
}
//JsonObject jsonObject = (JsonObject) object;
System.out.println( responseContentReader.toString());
the error message is
Exception in thread "main" java.lang.ClassCastException: com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
you forgot to close your json with brackets and braces like this:
{"vulnerabilities":[{"id":5027994,"status":"open","closed_at":null,"created_at":"2019-06-07T06:10:15Z","due_date":null,"notes":null,"port":[],"priority":null,"identifiers":["adobe-reader-apsb09-15-cve-2009-2990"],"last_seen_time":"2019-07-24T05:00:00.000Z","fix_id":4953,"scanner_vulnerabilities":[{"port":null,"external_unique_id":"adobe-reader-apsb09-15-cve-2009-2990","open":true}],"asset_id":119920,"connectors":[{"name":"Nexpose Enterprise","id":7,"connector_definition_name":"Nexpose Enterprise","vendor":"R7"}],"service_ticket":null,"urls":{"asset":"dummy.com"},"patch":true,"patch_published_at":"2009-10-08T22:40:52.000Z","cve_id":"CVE-2009-2990","cve_description":"Array index error in Adobe Reader and Acrobat 9.x before 9.2, 8.x before 8.1.7, and possibly 7.x through 7.1.4 might allow attackers to execute arbitrary code via unspecified vectors.","cve_published_at":"2009-10-19T22:30:00.000Z","description":null,"solution":null,"wasc_id":null,"severity":9,"threat":9,"popular_target":false,"active_internet_breach":true,"easily_exploitable":true,"malware_exploitable":true,"predicted_exploitable":false,"custom_fields":[],"first_found_on":"2019-06-05T05:22:23Z","top_priority":true,"risk_meter_score":100,"closed":false}]}
try this json and it should work!
I highly recommend you use this website for formmating your jsons
https://jsonformatter.org/
Instead of casting, retrieve the array from the object or json response like below:
JsonObject object = ...
JsonArray array = object.getJSONArray("vulnerabilities");
The response returned by the GET API is not a JsonArray but a JsonObject.
You can correct the following line -- JsonArray array = (JsonArray) object; to --
JsonObject jsonObject = (JsonObject) object;
Further, you could read the "vulnerabilities" within by --
JsonArray vulnerabilitiesArray = jsonObject.getJsonArray("vulnerabilities");

Simple JSON unexpected token { at position > 1

I'm trying to use JSON simple as part of a Java application to pull specific data from a .json file. Whenever I run the program, I get an unexpected token error message when it tries to parse.
A simplified version of the JSON file is as follows:
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"}
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
My code is as follows:
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) jsonObject.get("");
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this example, the line of code:
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
throws an error due to an unexpected token at the first left brace ({) of the second JSON object (i.e, at the brace before "id":345).
How could I go about resolving this issue?
And, as a follow up, how would one also pull the information for the username in this example?
Thanks for taking the time to read through this, and for any assistance provided!
That file is an invalid JSON file, it contains an entire object on each line.
What you'll need to do is read the file line by line, and then passing each line to the parser to create a new object.
If you fix your code, you can solve unexpected token error.
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
//You need to fix this part
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are trying to parse JSON object, and you actually have two JSON objects.
And in your code you are actually expect an array of JSON objects.
So, use the proper JSON array:
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
In order to quickly check your JSON syntax, you can use some online tool.
Your JSON is indeed wrong. It actually contains 2 valid JSONs. If you want to create one valid JSON document you have to wrap your input with { and } or [ ] if this is an array or collection. Please note the comma that separates 2 different entities.
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]

read text file which contains JSONs using java

I have a txt file. It contains all json's. below is the sample data..
{"userid": "0be57386-b081-41fc-b5c4-98103956371f","segments":["2_GMC_L"]}{"userid": "57f2f319-ed9b-4dc9-a550-70b51b724acb","segments":["2_GMC_L"]}
{"userid": "ba009949-f658-4abe-a707-d2b460ee2046","segments":["2_GMC_L"]}
I have to get the whole data one json by json.. as a string values. and print...
Use JSONParser class for parsing JSONString, find below sample code.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"/Users/Jiten/Documents/file1.txt"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
String author = (String) jsonObject.get("author");
JSONArray companyList = (JSONArray) jsonObject.get("companyList");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
System.out.println("\nCompany List:");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}

The method getJSONObject(String) is undefined for the type JSONObject

I am returning a json from my class:
#POST("/test")
#PermitAll
public JSONObject test(Map form) {
JSONObject json=new JSONObject();
json.put("key1",1);
json.put("key2",2);
return json;
}
now I want to get this json from "getInputStream" and parse it to see if key1 exists:
String output = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder output = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
output=output.toString();
JSONObject jsonObj = new JSONObject();
jsonObj.put("output", output);
if (jsonObj.get("output") != null){
**//search for key1 in output**
System.out.println("key1 exists");
}else{
System.out.println("key1 doesnt exist");
}
reader.close();
How can I convert output to JSONObject and search for "key1"?
I tried following but I got errors after arrows:
JSONObject jObject = new JSONObject(output); ---> The constructor JSONObject(String) is undefined
JSONObject data = jObject.getJSONObject("data"); ---> The method getJSONObject(String) is undefined for the type JSONObject
String projectname = data.getString("name"); ----> The method getString(String) is undefined for the type JSONObject
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
Try this.
And then you can verify the existence of the field using:
jsonObject.has("key1");
You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples

JSON Data Formatting

I am passing the following JSON object from a .jsp page to a java servlet using JSON.stringify and JQuery.ajax():
{"bin":[{"binId":"0","binDetails":[{"productCode":"AU192","qty":"4"},{"productCode":"NE823","qty":"8"}],"comments":"store pickup"},{"binId":"1","binDetails":[{"productCode":"AF634","qty":"2"}],"comments":""},{"binId":"2","binDetails":[{"productCode":"QB187","qty":"3"}],"comments":"international shipping"},{"binId":"3","binDetails":[{"productCode":"AF634","qty":"2"},{"productCode":"QB187","qty":"2"}],"comments":""}]}
This is the code in my java servlet:
StringBuffer strBuffer = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null){
strBuffer.append(line);
}
} catch (Exception e) {
}
try {
JSONObject jsonObj = new JSONObject(new JSONTokener(strBuffer.toString()));
// I call a method here and pass jsonObj
} catch (Exception e) {
}
In the method to which I pass jsonObj I am using jsonObj.length() to find out how many items are in jsonObj and it tells me 1, which in this case I would have expected 3. I even tried this:
JSONObject bins = jsonObj.get("bin");
bins.length();
which told me jsonObj.get("bin") was not a JSONObject. Is my data formatted incorrectly before I pass it from my .jsp or am I using the JSONObject in my java servlet incorrectly? How do I access the values in the JSONObject?
JSONArray bins = jsonObj.getJSONArray("bin");
bins.length();

Categories

Resources