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();
}
}
}
Related
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();
}
}
}
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;
}
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");
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();
}
I have a String of Json received from a web service http get request. I would like to turn the string that I have formed into a JsonObject.
The question has been answered perfectly. Please see answer below.
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.List;
import java.io.*;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class RetrieveData {
public static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) {
try {
String jsonString = (httpGet("http://kinseyreporter.org/API/list/reports/?tag=male%20victim&from=2012-06-02"));
JsonObject obj = new JsonObject();
Gson gson = new Gson();
System.out.println(jsonString);
List<String> list = new ArrayList<String>();
gson.fromJson(jsonString, (Type) list);
String json = gson.toJson(jsonString);
System.out.println(json);
} catch (Exception E) {
}
}
}
For that, you need to parse your flux json, here the code.
JsonObject root = (JsonObject)new JsonParser().parse(jsonString);
int i=0;
JsonObject dataReports
//get and print each object of reports
while(root.getAsJsonObject().get("reports").getAsJsonArray().size()>i && (dataReports=root.getAsJsonObject().get("reports").getAsJsonArray().get(i).getAsJsonObject())!=null){
System.out.println(dataReports.toString());
i++;
}