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

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();
}
}
}

Related

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();
}
}
}

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

I'm using the answer from another SO post and I'm getting an exception JSONArray cannot be converted to JSONObject. How can I get this resolved?

Here is the answer I'm using How to implement Login with HttpURLConnection and PHP server in Android
Here is my JSONParser.java:
package com.example.android.simplejson;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn; // Connection
DataOutputStream wr; // Write
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL("my_url");
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
try {
urlObj = new URL("my_url");
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
Log.d("Response: ", "> " + line); //here you'll get the whole response
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
Here is a snippet of my MainActivity.java:
class checkLogin extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
private ProgressDialog pd;
private static final String LOGIN_URL = "my_url";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Attempting login...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
protected JSONObject doInBackground(String... params) {
try {
HashMap<String, String> credentials = new HashMap<>();
credentials.put("username", params[0]);
credentials.put("password", params[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", credentials);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (json != null) {
Toast.makeText(MainActivity.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 1) {
Log.d("Success!", message);
} else {
Log.d("Failure", message);
}
}
}
}
It gets a JSONArray from the server [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]
My problem is the JSONArray can't be converted to JSONObject. So what can I change in my code to return the JSONArray as jObj? My ultimate goal is to set the text in my main activity as [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}].
Thanks!
You can't parse a JSON array as a JSON object. First you have to parse the payload as an array and then get the object from it.
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
// ...
try {
JSONArray jArr = new JSONArray(result.toString());
jObj = jArr.getJSONObject(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
Refer the below exampe :
String str = {"xyz":[{"name":"apple","email_id":"apple#apple.com"}]};
JSONObject json = JSONObject.fromObject(str);
So essentially your response is in format of a JSONArray [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]'
where it should have been something like
{"response": [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]}
or simply
{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}
depending on your preference. If you are always going to return a single JSONObject (probably as this is a login service response) there is no need to use the square braces which makes it a JSONArray.

How to fetch JSON object from Json array in REST API

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();
}

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