Exception Cast JsonObject - java

How can I read this file using JsonObject and JsonArray? And how can I retrieve the typeId value?
{
"mockup": {
"controls": {
"control": [
{
"ID": "5",
"measuredH": "400",
"measuredW": "450",
"properties": {
"bold": "true",
"bottomheight": "0",
"italic": "true",
"size": "20",
"text": "Test",
"topheight": "26",
"underline": "true",
"verticalScrollbar": "true"
},
"typeID": "TitleWindow",
"x": "50",
"y": "50",
"zOrder": "0"
},
{
"ID": "6",
"measuredH": "27",
"measuredW": "75",
"properties": {
"align": "left",
"bold": "true",
"color": "0",
"italic": "true",
"menuIcon": "true",
"size": "18",
"state": "selected",
"text": "OK",
"underline": "true"
},
"typeID": "Button",
"x": "67",
"y": "85",
"zOrder": "1"
}
]
},
"measuredH": "450",
"measuredW": "500",
"mockupH": "400",
"mockupW": "450",
"version": "1.0"
}
}
I'm using this code:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
private static final String _strDesktopDirectory = System.getProperty("user.home") + "/Desktop";
public static void main(String[] args) {
JSONParser _jspMyJsonParser = new JSONParser();
JFileChooser _fcMyFileChooser = new JFileChooser("Open JSON File");
FileNameExtensionFilter _fneJsonFilter = new FileNameExtensionFilter("JSON Files (*.json)", "json");
_fcMyFileChooser.setFileFilter(_fneJsonFilter);
int _iReturnFile = _fcMyFileChooser.showOpenDialog(_fcMyFileChooser);
_fcMyFileChooser.setCurrentDirectory(new File(_strDesktopDirectory));
if (_iReturnFile == JFileChooser.APPROVE_OPTION) {
try {
String _strSelectedFile = _fcMyFileChooser.getSelectedFile().toString();
Object _oMyObject = _jspMyJsonParser.parse(new FileReader(_strSelectedFile));
// Exception Here.
JSONObject _jsnoMockup = (JSONObject) _oMyObject;
_jsnoMockup = (JSONObject) _jsnoMockup.get("mockup");
JSONObject _jsnoControls = (JSONObject) _jsnoMockup.get("controls");
System.out.println("Mockup: " + _jsnoMockup);
System.out.println("Controls: " + _jsnoControls);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
} else {
System.out.println("Close");
System.exit(0);
}
}
}
The error is:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.JSONObject
Note: I don't have any experience with Java.
The method getJSONfromURL returns the JSON of the given URL and that works just fine but the error is in JSONArray jsonArray = (JSONArray)jsonobject;
It gives the following error: cannot cast JSONObject to JSONArray. I've also tried this: JSONArray jsonArray = (JSONObject)(JSONArray)jsonobject;
I can't figure out what I'm doing wrong.

try with below one
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.getJSONObject("mockup").getJSONObject("controls").getJSONArray("control");
for(i=0;i<jsonArray.lenght();i++){
System.out.println(jsonArray.getJSONObject(i).getString("typeID"));
}

Related

Json Object not Displaying in Java

I want to get "weather" data from JSONObject but this error is coming.
org.json.JSONException: JSONObject["weather"] not a string.
at org.json.JSONObject.getString(JSONObject.java:639)
at GetWeather.main(GetWeather.java:49)
This is my code
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetWeather {
public static String getWeather(String args){
String result =" ";
URL url ;
HttpURLConnection urlConnection = null;
try{
url = new URL(args);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data= reader.read();
while(data!=-1){
char current=(char) data;
result += current;
data= reader.read();
}
return result;
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//main
public static void main(String[] args){
String s1 = getWeather(args[0]);
try {
JSONObject jsonObject = new JSONObject(s1);
String weather= jsonObject.getString("weather");
System.out.println(weather);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the string which I am passing
http://api.openweathermap.org/data/2.5/weather?q=Delhi&APPID=04b767167643ea6af521695e7948e0fb
This is the data I get back
{"coord":{"lon":77.22,"lat":28.67},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50d"}],"base":"stations","main":{"temp":305.86,"pressure":1007,"humidity":38,"temp_min":304.15,"temp_max":307.15},"visibility":3500,"wind":{"speed":1.5,"deg":320},"clouds":{"all":0},"dt":1508241600,"sys":{"type":1,"id":7808,"message":0.0051,"country":"IN","sunrise":1508201604,"sunset":1508242734},"id":1273294,"name":"Delhi","cod":200}
Which in formatted version looks like
{
"coord": {
"lon": 77.22,
"lat": 28.67
},
"weather": [{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.86,
"pressure": 1007,
"humidity": 38,
"temp_min": 304.15,
"temp_max": 307.15
},
"visibility": 3500,
"wind": {
"speed": 1.5,
"deg": 320
},
"clouds": {
"all": 0
},
"dt": 1508241600,
"sys": {
"type": 1,
"id": 7808,
"message": 0.0051,
"country": "IN",
"sunrise": 1508201604,
"sunset": 1508242734
},
"id": 1273294,
"name": "Delhi",
"cod": 200
}
Please tell me whats wrong with my code and what to do.
The value of "weather" that you're trying to get is not a String, but a JSONArray.
In order to read all the information inside it, try using getJSONArray():
try {
JSONObject jsonObject = new JSONObject(s1);
// read the `weather` content
JSONArray weatherArray = jsonObject.getJSONArray("weather");
// get only the first element of `weather`, the only one existing
JSONObject weatherObject = (JSONObject)weatherArray.get(0);
// read all its' properties
for (Object key : weatherObject.keySet()) {
System.out.println("key:" + key + ", value: " + weatherObject.get((String)key));
}
} catch (JSONException e) {
e.printStackTrace();
}
For other info like "temp" or "pressure", just use getJSONObject() since "main" has JSONObject type:
JSONObject mainObject = jsonObject.getJSONObject("main");
System.out.println("pressure value: " + mainObject.get("pressure"));
System.out.println("temp value: " + mainObject.get("temp"));

How to parse JSON on Java

I have the following JSON text that I need to parse to get "id": 176514,
What is the required code?
{
"response": {
"count": 10307,
"items": [
{
"id": 176514,
"from_id": -114200945,
"owner_id": -114200945,
"date": 1506629224,
"marked_as_ads": 0,
"post_type": "post",
"text": "-я с разбитым сердцем сука,но я всё равно влюблённый.",
"post_source": {
"type": "api"
},
"comments": {
"count": 1,
"groups_can_post": true,
"can_post": 1
},
"likes": {
"count": 103,
"user_likes": 0,
"can_like": 1,
"can_publish": 1
},
"reposts": {
"count": 3,
"user_reposted": 0
},
"views": {
"count": 1022
}
}
]
}
}
I try some times but.. (
my code
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
class VK{
public static void main(String [] args) throws IOException{
URL url = new URL("my url which return JSON structure");
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
JSONObject obj = new JSONObject(str);
JSONObject res = obj.getJSONArray("items").getJSONObject(0);
System.out.println(res.getInt("id"));
}
}
Eclipse
my errors:
Exception in thread "main" org.json.JSONException: JSONObject["items"] not found.
at org.json.JSONObject.get(JSONObject.java:472)
at org.json.JSONObject.getJSONArray(JSONObject.java:619)
at VK.main(VK.java:26)
You need to go one more level deep.
JSONObject obj = new JSONObject(str);
JSONObject firstItem = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0);
System.out.println(firstItem.getInt("id"));
try this:
JSONObject obj = new JSONObject(str);//assuming that obj is the same object as in the example
//to get the id
int id = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0).getInt("id");
In case that you are parsing Array of objects
JSONArray jsonArray = new JSONArray(stringToParse);
than continue as usual

Convert JsonArray to JsonObject

I have this JSON array:
[{
"MOTIVO": "ok",
"ESTATUS": "10",
"TIPO": "1",
"ACCMOTIDN": "2",
"AVMVOR1IDN": "31089",
"AVMVORIDN": "23163",
"SPCHRZIDN": "75"
}, {
"MOTIVO": "ok",
"ESTATUS": "10",
"TIPO": "1",
"ACCMOTIDN": "2",
"AVMVOR1IDN": "31090",
"AVMVORIDN": "23163",
"SPCHRZIDN": "75"
}]
I validate with JSONLint and it is a valid JSON. How can I convert into a jsonObjects? This is what I have at this moment:
public ArrayList<Object[]>Auth_Rej_Order(String obj_auth,mPedidoDet
mpedidodet)
{
try
{
res_array=new ArrayList();
obj_auth_json=new JSONArray(obj_auth);
obj_auth_list=new ArrayList<>();
obj_auth_list_map=new HashMap<>();
JSONObject obj_json;
for(int i= obj_auth_json.length()-1;i>=0;i--)
{
obj_json=new JSONObject(obj_auth_json);
Iterator<?> keys = obj_json.keys();
while( keys.hasNext() )
{
String key = keys.next().toString();
obj_auth_list_map.put(key,obj_json.get(key));
}
obj_auth_list.add(obj_auth_list_map);
}
}
catch(Exception ex)
{
//Error inesperado.
res_array.clear();
res_obj_array=new Object[1];
res_obj_array[0]="001";
res_array.add(res_obj_array);
}
return res_array;
}
I'm trying with:
obj_json=new JSONObject(obj_auth_json)
obj_json=new JSONObject(obj_auth_json.get(position))
obj_json=new JSONObject(obj_auth_json.getJSONObject(position))
obj_json=new JSONObject(obj_auth_json.getJSONArray(position));
and any of them worked.

Nested JSON Array in Java

I need to create a json response like the one below. I tried with some code but couldn't able to get what i need. Need help in java code to create nested array to group the food items according to the categories along with the category details like in below json
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}
}
What i tried so far will give response in one single array.
#Path("/items")
public class HotelsMenu {
#GET
#Path("/getitems")
#Produces(MediaType.APPLICATION_JSON)
public String doLogin(#QueryParam("hotelcode") String hotelcode) {
JSONObject response = new JSONObject();
JSONArray hotelDetails = checkCredentials(hotelcode);
try {
response.put("hotels", hotelDetails);
response.put("status", (hotelDetails == new JSONArray()) ? "false" : "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.toString();
}
private JSONArray checkCredentials(String hotelcode) {
System.out.println("Inside checkCredentials");
JSONArray result = new JSONArray();
try {
result = DBConnection.checkItems(hotelcode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static JSONArray checkItems(String hotelcode) throws Exception {
int id;
String code = hotelcode + "_mnu";
String name = null;
String name1 = null;
String status;
String price;
Connection dbConn = null;
Connection dbConn1 = null;
JSONArray hotels = new JSONArray();
JSONArray menu = new JSONArray();
try {
try {
dbConn = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt = dbConn.createStatement();
String query = "SELECT * FROM " + code + " where Status='1'";
System.out.println(query);
ResultSet rs1 = stmt.executeQuery(query);
System.out.println("hai");
while (rs1.next()) {
JSONObject hotel = new JSONObject();
id = rs1.getInt("Id");
hotel.put("id", id);
code = rs1.getString("Code");
System.out.println(code);
hotel.put("code", code);
name = rs1.getString("Name");
hotel.put("name", name);
status = rs1.getString("Status");
hotel.put("status", status);
hotels.put(hotel);
System.out.println("Hotel1:" + hotels);
try {
dbConn1 = DBConnection.createConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Statement stmt1 = dbConn1.createStatement();
String query1 = "SELECT * FROM " + code + " where Status='1' ";
System.out.println(query1);
ResultSet rs2 = stmt1.executeQuery(query1);
while (rs2.next()) {
JSONArray hotel1 = new JSONArray();
JSONObject hotelmenu = new JSONObject();
id = rs2.getInt("Id");
hotelmenu.put("id", id);
name1 = rs2.getString("Name");
hotelmenu.put("name", name1);
price = rs2.getString("Price");
hotelmenu.put("price", price);
hotel1.put(hotelmenu);
hotels.put(hotel1);
System.out.println(hotels);
}
}
} catch (SQLException sqle) {
throw sqle;
} catch (Exception e) {
// TODO Auto-generated catch block
if (dbConn != null) {
dbConn.close();
}
throw e;
} finally {
if (dbConn != null) {
dbConn.close();
}
}
return hotels;
}
}
As previous answers suggests, you should re-design your model. I just did a quick restructuring of it. Check if this serves your purpose -
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}}
If the structure is OK, let know if you want help with the Java code to generate the above Json.
Also maybe go through the following libraries -
Jackson tutorial and Gson tutorial
//import java.util.ArrayList;
//import org.bson.Document;
Document root = new Document();
Document rootMenu = new Document();
ArrayList rootMenuItems = new ArrayList();
Document rootMenuItems0 = new Document();
ArrayList rootMenuItems0Sub_items = new ArrayList();
Document rootMenuItems0Sub_items0 = new Document();
Document rootMenuItems0Sub_items1 = new Document();
Document rootMenuItems1 = new Document();
ArrayList rootMenuItems1Sub_items = new ArrayList();
Document rootMenuItems1Sub_items0 = new Document();
Document rootMenuItems2 = new Document();
ArrayList rootMenuItems2Sub_items = new ArrayList();
Document rootMenuItems2Sub_items0 = new Document();
Document rootMenuItems2Sub_items1 = new Document();
rootMenuItems0.append("id", 1);
rootMenuItems0.append("code", "hot1_sub1_mnu");
rootMenuItems0.append("name", "Mutton");
rootMenuItems0.append("status", "1");
rootMenuItems0Sub_items0.append("id", "01");
rootMenuItems0Sub_items0.append("name", "Mutton Pepper Fry");
rootMenuItems0Sub_items0.append("price", "100");
rootMenuItems0Sub_items1.append("id", "02");
rootMenuItems0Sub_items1.append("name", "Mutton Curry");
rootMenuItems0Sub_items1.append("price", "100");
rootMenuItems1.append("id", "2");
rootMenuItems1.append("code", "hot1_sub2_mnu");
rootMenuItems1.append("name", "Sea Food");
rootMenuItems1.append("status", "1");
rootMenuItems1Sub_items0.append("id", "01");
rootMenuItems1Sub_items0.append("name", "Fish Fry");
rootMenuItems1Sub_items0.append("price", "150");
rootMenuItems2.append("id", "3");
rootMenuItems2.append("code", "hot1_sub3_mnu");
rootMenuItems2.append("name", "Noodles");
rootMenuItems2.append("status", "1");
rootMenuItems2Sub_items0.append("id", "01");
rootMenuItems2Sub_items0.append("name", "Chicken Noodles");
rootMenuItems2Sub_items0.append("price", "70");
rootMenuItems2Sub_items1.append("id", "02");
rootMenuItems2Sub_items1.append("name", "Egg Noodles");
rootMenuItems2Sub_items1.append("price", "60");
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items0.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items0);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0Sub_items1.isEmpty()) {
rootMenuItems0Sub_items.add(rootMenuItems0Sub_items1);
}
if (!rootMenuItems0Sub_items.isEmpty()) {
rootMenuItems0.append("sub_items", rootMenuItems0Sub_items);
}
if (!rootMenuItems0.isEmpty()) {
rootMenuItems.add(rootMenuItems0);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1Sub_items0.isEmpty()) {
rootMenuItems1Sub_items.add(rootMenuItems1Sub_items0);
}
if (!rootMenuItems1Sub_items.isEmpty()) {
rootMenuItems1.append("sub_items", rootMenuItems1Sub_items);
}
if (!rootMenuItems1.isEmpty()) {
rootMenuItems.add(rootMenuItems1);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items0.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items0);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2Sub_items1.isEmpty()) {
rootMenuItems2Sub_items.add(rootMenuItems2Sub_items1);
}
if (!rootMenuItems2Sub_items.isEmpty()) {
rootMenuItems2.append("sub_items", rootMenuItems2Sub_items);
}
if (!rootMenuItems2.isEmpty()) {
rootMenuItems.add(rootMenuItems2);
}
if (!rootMenuItems.isEmpty()) {
rootMenu.append("items", rootMenuItems);
}
if (!rootMenu.isEmpty()) {
root.append("menu", rootMenu);
}
System.out.println(root.toJson());

Parse and Sort JSON data using java

I am looking to parse the following array using org.json.simple library and having difficulty. Could someone please look at my json file and code and advise what I am doing wrong
{
"Company": [
{
"Department": "Engineering",
"Employee": [
{
"EmpName": "Jack",
"EmpCode": "8",
"Type": "Permanent"
}, {
"EmpName": "John",
"EmpCode": "45",
"Type": "Permanent"
}, {
"EmpName": "Ron",
"EmpCode": "9",
"Type": "Contract"
}, {
"EmpName": "Jin",
"EmpCode": "6",
"Type": "Permanent"
}, {
"EmpName": "Jill",
"EmpCode": "",
"Type": "Retired"
}, {
"EmpName": "Sam",
"EmpCode": "89",
"Type": "Permanent"
}, {
"EmpName": "Jonathan",
"EmpCode": "66",
"Type": "Permanent"
}, {
"EmpName": "Craig",
"EmpCode": "",
"Type": "Ex-Employee"
}, {
"EmpName": "Son Hui",
"EmpCode": "4",
"Type": "Permanent"
}, {
"EmpName": "Joshua",
"EmpCode": "12",
"Type": "Contract"
}, {
"EmpName": "Tulip",
"EmpCode": "70",
"Type": "Contract"
}
]
}, {
"Department": "IT",
"Employee": [
{
"EmpName": "Nico",
"EmpCode": "50",
"Type": "Resigned"
}, {
"EmpName": "Phil",
"EmpCode": "103",
"Type": "Resigned"
}
]
}
]
}
Notice that a few EmpCode fields are also blank. How should I handle them. Also, I need to be able to re-arrange the data while displaying it, I mean I need to sort the data based on EmpCode or Type.
The code I wrote to parse the above json is mentioned below:
package amazontesting;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
public class json {
private static final String filePath = /emp.json";
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(filePath));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Department");
//String suites = (String) jsonObject.get("Company");
JSONArray slideContent = (JSONArray) jsonObject.get("Department");
Iterator i = slideContent.iterator();
while (i.hasNext()) {
System.out.println(i.next());
String title = (String) jsonObject.get("Employee");
System.out.println(title);
}
}
catch (FileNotFoundException e)
{}
catch(IOException e)
{}
catch(ParseException e)
{}
}
}
Looks like you have misunderstanding of how Json structure works and what kind of objects it's may contains.
For example, what do you think you do in this piece of code?
JSONArray slideContent = (JSONArray) jsonObject.get("Department");
Iterator i = slideContent.iterator();
Looks like you trying to get json object with name "Department", but it's not an JsonArray, it's a String.
"Department": "Engineering"
//Writing code "jsonObject.get("Department")"
//you will get string "Engineering"
//this code will be correct
(JSONArray) jsonObject.get("Employee")
//because a json value for name "Employee" it's an JsonArray

Categories

Resources