How to fetch JSON object from Json array in REST API - java

I am new to REST API and handling JSON in our automation script. I have an API whose response is JSONArray i.e.,
[{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]
While automation, for verification I need to fetch the reponse. I have tried the below one but not getting expected output
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import org.json.*;
public class ProjectNameVerfication {
public static void main(String[] args) throws JSONException
{
try
{
URL url = new URL("http://17*.**.**.**:3000/api/******");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200)
{
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
System.out.println("str : " + str);
JSONObject obj = new JSONObject(str.substring(str.indexOf('{')));
System.out.println("obj : " +obj);
int ProjectID = obj.optInt("ProjectID");
String ProjectName = obj.getString("ProjectName");
System.out.println("ProjectID: " +ProjectID);
System.out.println("ProjectName: " +ProjectName);
JSONArray arr = obj.getJSONArray("ProjectID");
for (int i = 0; i < arr.length(); i++)
{
String post_id =arr.getJSONObject(i).getString("ProjectName");
}
conn.disconnect();
}
catch (MalformedURLException e) { e.printStackTrace();}
catch (IOException e) { e.printStackTrace(); }
}
}
Actual output is bellow:
str : [{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]
obj : {"ProjectName":" securities""ProjectID":15}
ProjectID: 15
ProjectName: Securities
Exception in thread "main" org.json.JSONException: JSONObject["ProjectID"] is not a JSONArray.
at org.json.JSONObject.getJSONArray(JSONObject.java:539)
at MyTest.ProjectNameVerfication.main(ProjectNameVerfication.java:60)

You want to get all ProjectName,right?
look at your response data:
[{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]
it is already a JSONArray string,you can parse it as JSONArray ,and get ProjectName in foreach
JSONArray jsonArray = new JSONArray("your str");
for (Object object : jsonArray) {
JSONObject jsonObject = (JSONObject)object;
System.out.println(jsonObject.toString());
}

If you are using simple JSON you have to parse as follows.
String str="[{\"ProjectID\":15,\"ProjectName\":\" Securities\"},
{\"ProjectID\":16,\"ProjectName\":\"PAS \"}]";
JSONParser json=new JSONParser();
try {
JSONArray arr=(JSONArray)json.parse(str);
for (int i = 0; i < arr.size(); i++) {
JSONObject obj=(JSONObject)arr.get(i);
System.out.println("ProjectID: "+obj.get("ProjectID"));
System.out.println("ProjectName: "+obj.get("ProjectName"));
}
} catch (ParseException e) {
e.printStackTrace();
}

Your response is an Array so you need JSONArray instead of JSONObject.
try {
JSONArray e = new JSONArray(str);
int l = e.length();
for (int x = 0; x < l; x++) {
JSONObject object1 = e.getJSONObject(x);
String projectID = object1.getString("ProjectID");
String projectName = object1.getString("ProjectName");
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Why am I getting this error ?? java.lang.ClasscastException

I am unable to resolve the issue.. please help:
Erorr:
java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.simple.JSONObject (org.json.simple.JSONArray and org.json.simple.JSONObject are in module json.simple#1.1 of loader 'app')
at lamda_pi/lamda_pi.letsRead.main(letsRead.java:77)
Sample json looks like below:
[
{
"name": "Afghanistan",
"dial_code": "+93",
"code": "AF"
},
{
"name": "Aland Islands",
"dial_code": "+358",
"code": "AX"
}]
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class letsRead
{
public static void main(String [] args)
{
String inline = "";
try
{
URL url = new URL("https://gist.githubusercontent.com/anubhavshrimal/75f6183458db8c453306f93521e93d37/raw/f77e7598a8503f1f70528ae1cbf9f66755698a16/CountryCodes.json");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
System.out.println("Response code is: " +responsecode);
if(responsecode != 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else
{
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline=inline + sc.nextLine();
}
System.out.println("\nJSON Response in String format");
System.out.println(inline);
sc.close();
}
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject)parse.parse(inline);
JSONArray jsonarr_1 = (JSONArray) jobj.get("name");
for(int i=0;i<jsonarr_1.size();i++)
{
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
System.out.println(jsonobj_1.get("name"));
}
conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The top level object in your JSON file is an array so:
class letsRead
{
public static void main(String [] args)
{
String inline = "";
try
{
URL url = new URL("https://gist.githubusercontent.com/anubhavshrimal/75f6183458db8c453306f93521e93d37/raw/f77e7598a8503f1f70528ae1cbf9f66755698a16/CountryCodes.json");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
System.out.println("Response code is: " +responsecode);
if(responsecode != 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else
{
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext())
{
inline=inline + sc.nextLine();
}
System.out.println("\nJSON Response in String format");
System.out.println(inline);
sc.close();
}
JSONParser parse = new JSONParser();
JSONArray jsonarr_1 = (JSONArray)parse.parse(inline);
for(int i=0;i<jsonarr_1.size();i++)
{
JSONObject jsonobj_1 = (JSONObject)jsonarr_1.get(i);
System.out.println(jsonobj_1.get("name"));
}
conn.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

How to Split a JsonElement

So I was wondering how I could get an individual part of a JsonElement as when I run the program each element contains more information in it.
For example, it prints one of the elements in the JsonArray as [94372,1100000,1389792,31,43]
How would I be able to retrieve only the first number in the element?
import com.google.gson.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String inline = "";
try{
URL url = new URL("http://api.gw2tp.com/1/bulk/items.json");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode!= 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else {
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()){
inline+=sc.nextLine();
}
}
JsonParser parse = new JsonParser();
JsonObject jobj = (JsonObject)parse.parse(inline);
JsonElement updated = jobj.get("updated");
JsonArray jsonarr_1=(JsonArray)jobj.get("items");
JsonArray jsonarr_2=(JsonArray)jobj.get("columns");
System.out.println(jsonarr_2);
for(int i=0;i<jsonarr_1.size();i++) {
System.out.println(jsonarr_1.get(i));
}
}catch (Exception e){
e.printStackTrace();
}
}
}
That object is a JSONArray, calling .getAsJsonArray().get(0) will get its first entry:
System.out.println(jsonarr_1.get(0).getAsJsonArray().get(0));
outputs:
24
System.out.println(jsonarr_1.get(i).getAsJsonArray().get(0)); in your loop will output the first element of each array.
full code:
import com.google.gson.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String inline = "";
try{
URL url = new URL("http://api.gw2tp.com/1/bulk/items.json");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode!= 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else {
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()){
inline+=sc.nextLine();
}
}
JsonParser parse = new JsonParser();
JsonObject jobj = (JsonObject)parse.parse(inline);
JsonElement updated = jobj.get("updated");
JsonArray jsonarr_1=(JsonArray)jobj.get("items");
JsonArray jsonarr_2=(JsonArray)jobj.get("columns");
System.out.println(jsonarr_2);
for(int i=0;i<jsonarr_1.size();i++) {
System.out.println(jsonarr_1.get(i).getAsJsonArray().get(0));
}
}catch (Exception e){
e.printStackTrace();
}
}
}

A JSONArray text must start with '[' at 2 [character 3 line 1]

I have written the following code to get the JSON response from the url which has authentication. Further,this response is in the format of the JSON array. Response is kind of big so I have attached JSON response in the following link:
https://drive.google.com/file/d/1-gSM1CXQlB7eJQXXsY8_G3koJWuyZB8S/view?usp=sharing
I want to fetch the user id and their role in the form of JSON object. However I'm facing this error.Can anybody help me what went wrong and could you suggest any modification in the code?
package url_request;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParing {
private static HttpURLConnection connection;
public static void main(String args[]) {
String usernameColonPassword = "uname:pass";
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("https://ucf6-zfon-fa-ext.oracledemos.com/hcmRestApi/scim/Users");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
// for testing the connection
// System.out.println(status);
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
}
// System.out.println(responseContent.toString());
parse(responseContent.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
} finally {
connection.disconnect();
}
}
public static String parse(String responseBody) {
JSONArray albums;
try {
albums = new JSONArray(responseBody);
for (int i = 0; i < albums.length(); i ++) {
JSONObject album = albums.getJSONObject(i);
int id = album.getInt("id");
int role = album.getInt("roles");
System.out.println(id + " " + role);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
In the uname and pass fields, I will add the credential of the URL.
This code works for your example, althought I had to change some types, there were problems with casting
public static Map<String, Set<String>> parse(String responseBody) {
JSONObject resourcesNode = new JSONObject(responseBody); // incoming payload is an object, not an Array
Map<String, Set<String>> result = new HashMap<>();
try {
JSONArray albums = resourcesNode.getJSONArray("Resources"); // get to the
//Resource array, that holds desired data
for (int i = 0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
String id = album.getString("id"); //id was type of String, not int
if(album.has("roles")){ // not all entries had roles, safety check
Set<String> userRoles =new HashSet<>();
JSONArray roles = album.getJSONArray("roles");
for(int j=0;j<roles.length();j++){
userRoles.add(roles.get(j).toString());
}
results.put(id, userRoles);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return results;
}

Converting JSONObject to JSONArray Exception

I have a website that I have to make queries on in Java. Here you can see the dataset
https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31
At the very first beginning, I thought this is a JSONArray, but Eclipse always told me, it is not.
So therefore I tried to convert from JSONObject to JSONArray but I get this error:
org.json.JSONException: JSONObject["dataset"] is not a JSONArray.
What am I doing wrong?
Here is my code:
package query;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;
import java.io.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Stockquery {
public static void main(String[] args) {
String jsonString = callURL(
"https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31");
// System.out.println("\n\njsonString: " + jsonString);
try {
JSONObject jsonobjects = new JSONObject(jsonString);
System.out.println("\n\njsonArray: " + jsonobjects);
JSONArray arr = jsonobjects.getJSONArray("dataset");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String callURL(String myURL) {
// System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
}
The dataset field of jsonobjects is a JSONObject not JSONArray. Change this:
jsonobjects.getJSONArray("dataset");
to this:
JSONObject dataset = jsonobjects.getJSONObject("dataset");
JSONArray array = dataset.getJSONArray("data");

Value https of type java.lang.String cannot be converted to JSONArray

I am trying to get Json String from json Array but got this error, Any help will be highly appreciated, Json formate is given bellow please help someone.
Error is as bellow
05-29 12:37:22.600 25505-25505/com.akasha.mongodataapi W/System.err: org.json.JSONException: Value https of type java.lang.String cannot be converted to JSONArray
05-29 12:37:22.610 25505-25505/com.akasha.mongodataapi W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
05-29 12:37:22.610 25505-25505/com.akasha.mongodataapi W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
05-29 12:37:22.610 25505-25505/com.akasha.mongodataapi W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
It is the Json Formate
[ { "_id" : { "$oid" : "57472009a0fdab7cc3c"} , "name" : "Sasha Burni" , "sort" : "Sasha"} ,
{ "_id" : { "$oid" : "57472009afdab7cc3d"} , "name" : "Akasha Khail" , "sort" : "Akasha"}]
And the Java Code is as bellow
String url="https://api.mlab.com/api/1/databases/picasanovels/collections/Country?apiKey=myapikey";
try {
JSONArray jArr = new JSONArray(url);
for (int count = 0; count < jArr.length(); count++) {
JSONObject obj = jArr.getJSONObject(count);
String name = obj.getString("name");
System.out.println("Name Printed :"+name);
//so on
}
} catch (JSONException e) {
e.printStackTrace();
}
You are trying passing the API call (url address) to JSON ARRAY. It should be the response from the API call.
You have to create a URL object and pass the Url to the constructor.
Then you have to open up a new connection using HttpUrlConnection class.
I have included the complete code below for your reference. Please feel free to ask if you need more help. Thanks
package com.pragin.ocjp;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JsonExample {
public String jsonEx(){
String url = " https://api.tfl.gov.uk/Place?lat=51.555504&lon=0.0592359&radius=80&includeChildren=False&type=NaptanPublicBusCoachTram&app_id=95a7b158&app_key=a3acd48055f470cf35ab5f6f360604c5";
URL obj;
BufferedReader reader;
StringBuilder stringBuilder;
HttpURLConnection con;
stringBuilder = new StringBuilder();
try {
obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode(); // to check success and failure of API call
System.out.println("Response Code : " + responseCode);
String response = con.getResponseMessage();
System.out.println("Response : " + response.toString());
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
System.out.println("String : " + stringBuilder.toString());
}
//return stringBuilder.toString();
}catch(IOException e){
System.out.println("Error" + e);
}
return stringBuilder.toString();
}
public void jsonParser(String res) throws ParseException {
JSONParser jParse = new JSONParser();
JSONObject jsonObject = (JSONObject) jParse.parse(res);
System.out.println("res = [" + jsonObject.size() + "]");
for(int i = 0; i <jsonObject.size(); i++ ){
// JSONObject jsonObject = (JSONObject) jArray.get(i);
// jsonObject.
String name = (String) jsonObject.get("$type");
System.out.println("Name : " + name);
}
}
public static void main(String[] args) throws ParseException {
JsonExample js = new JsonExample();
js.jsonParser(js.jsonEx());
}
}`

Categories

Resources