AutoSuggest in Android from jsonencoded array of php - java

I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
try {
String temp=sName.replace(" ", "%20");
URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for(int i = 0; i < jsonResponse.length(); i++){
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
}
}

As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);
Try changing that to:
JSONArray jsonResponse = new JSONArray(line);

You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);

Related

Get String value of json array in a json

For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.

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

Parse JSON response into a List

I'm trying to parse a JSON response
it's structure is:
{
"metric": {
"name": "string",
"values": [
"string"
]
}
}
My code so far:
StringBuilder sb = new StringBuilder();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
wr.close();
reader.close();
JSONObject json = new JSONObject(sb.toString());
JSONArray jsonArray = json.getJSONArray("values");
List<String> list = new ArrayList<>();
String errorPercent ="";
for(int i = 0 ; i < json.length() ; i++){
errorPercent = jsonArray.getJSONArray(i).getString(i);
list.add(errorPercent);
}
The output I'm getting is saying that "values " was not found,
am I misunderstanding the structure of the JSON response?
Edit
It appears the structure I was given on the site I'm receiving the response from is not correct. it appears to be a more complicated structure
I have modified my code accordingly:
JSONObject json = new JSONObject(sb.toString());
JSONObject metricsData = json.getJSONObject("metric_data");
JSONArray metrics = metricsData.getJSONArray("metrics");
System.out.println(metrics.toString());
The print out is as follows:
[{"timeslices":[{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},"from":"2015-10-25T22:39:00+00:00","to":"2015-10-25T22:40:00+00:00"},{"values":{"max_response_time":0,"calls_per_minute":0,"average_be_response_time":0,"error_percentage":0,"min_response_time":0,"requests_per_minute":0,"average_network_time":0,"average_response_time":0,"average_fe_response_time":0,"total_app_time":0,"call_count":0,"fe_time_percentage":0,"total_network_time":0,"total_fe_time":0,"network_time_percentage":0},
There appears to be another array within the array: "timeslices" is that right? how do I get at that array?
I unsuccessfully tried:
JSONArray timeslices = metrics.getJSONArray("timeslices");
values is a field inside metric.
You'd need to first get the metric object, then look inside that for values.
JSONObject metric = json.getJSONObject("metric");
JSONArray jsonArray = metric.getJSONArray("values");

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

Convert a .json file to a JSONArray

I used cURL to get some twitter feeds in the form of a json file ("twitter-feed.json"). I want to convert this json file to a JSONArray object. How do I do it?
I am new to Java and json. Your suggestions are most welcome.
FileInputStream infile = new FileInputStream("input/twitter-feed.json");
// parse JSON
JSONArray jsonArray = new JSONArray(string);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
Thanks,
PD.
You need to read the file first, convert it to String then feed it to the JSONArray (I am assuming that you are using the JSON-Java Project. The code below illustrates how to read the file and set it to JSONArray
// read the source file, source comes from streaming API delimited by newline
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);
ArrayList jsonObjectArray = new ArrayList();
String currentJSONString = "";
// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
// create new JSONObject
JSONObject currentObject = new JSONObject(currentJSONString);
// there are more than one way to do this, right now what I am doing is adding
// each JSONObject to an ArrayList
jsonObjectArray.add(currentObject);
}
for (int i = 0; i < jsonObjectArray.size(); i++) {
JSONObject jsonObject = jsonObjectArray.get(i);
// check if it has valid ID as delete won't have one
// sample of JSON for delete :
// {"delete":{"status":{"user_id_str":"50269460","id_str":"121202089660661760","id":121202089660661760,"user_id":50269460}}}
if(jsonObject.has("id")) {
System.out.println(jsonObject.getInt("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at") + "\n");
}
}
Steps explanation :
Stream API does not provide valid JSON as a whole but rather a valid one specified by the delimited field. Which is why, you can't just parse the entire result as is.
In order to parse the JSON, I use the delimited to use newline since BufferedReader has a method readLine that we could directly use to get each JSONObject
Once I get each valid JSON from each line, I create JSONObject and add it to the ArrayList
I then iterate each JSONObject in the ArrayList and print out the result. Note that if you want to use the result immediately and don't have the need to use it later, you can do the processing itself in while loop without storing them in the ArrayList which change the code to:
// read the source file, source comes from streaming API
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);
String currentJSONString = "";
// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
// create new JSONObject
JSONObject currentObject = new JSONObject(currentJSONString);
// check if it has valid ID as delete status won't have one
if(currentObject.has("id")) {
System.out.println(currentObject.getInt("id"));
System.out.println(currentObject.getString("text"));
System.out.println(currentObject.getString("created_at") + "\n");
}
}
You may try Gson:
For just arrays you can use:
Gson gson = new Gson();
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
To deserialize an array of objects, you can just do:
Container container = new Gson().fromJson(json, Container.class);
As shown here
Use ObjectMapper Class from jackson library like this :
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Categories

Resources