Related
I have this JSON response:
"objects":{
"5": [
[
{
"id_lot_espace": 0,
"id_lot_objet": "0",
"id_objet_piece": 0,
"params": {
"auto": "1",
"objLink": "0",
"setpointM": "7",
"setpoint0": "21",
"setpoint1": "19",
"setpointA": "16",
"tempSocialJ": "19",
"tempSocialN": "17",
"tempMin": "7",
"tempMax": "30",
"tempFrom": "2018-10-15",
"tempTo": "2019-04-15"
},
"label": "migo",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "zwave_device_fab36177_node6_thermostat_setpoint_heating",
"renommable": "0",
"id_famille": 5,
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
]
],
"17": {
"381": {
"19": {
"id_lot_espace": "381",
"id_lot_objet": "0",
"id_objet_piece": "19",
"params": "",
"label": "Pièce principale - Tête thermostatique",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "",
"renommable": "0",
"id_famille": "17",
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
}
}
}
}
I want to access pieceLabel in each element. Here’s what I’ve tried so far:
job = new JSONObject(responseContent);
JSONObject object = job.getJSONObject("objects");
Iterator<String> it = object.keys();
while (it.hasNext()) {
String key = it.next();
JSONObject obj1 = object.getJSONObject(key);
Iterator<String> it1 = obj1.keys();
while (it1.hasNext()) {
String key1 = it1.next();
JSONObject obj2 = obj1.getJSONObject(key1);
Iterator<String> it2 = obj2.keys();
while (it2.hasNext()) {
String key2 = it2.next();
final JSONObject obj3 = obj2.getJSONObject(key2);
String pieceLabel = String.valueOf(obj3.get("pieceLabel"));
}
}
}
Please check your json its having issue. You can use many tools online to check your json if its proper or not.
I usually use https://codebeautify.org/jsonviewer
Corrected Json
[
[
{
"id_lot_espace": 0,
"id_lot_objet": "0",
"id_objet_piece": 0,
"params": {
"auto": "1",
"objLink": "0",
"setpointM": "7",
"setpoint0": "21",
"setpoint1": "19",
"setpointA": "16",
"tempSocialJ": "19",
"tempSocialN": "17",
"tempMin": "7",
"tempMax": "30",
"tempFrom": "2018-10-15",
"tempTo": "2019-04-15"
},
"label": "migo",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "zwave_device_fab36177_node6_thermostat_setpoint_heating",
"renommable": "0",
"id_famille": 5,
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
]
]
{
"17": {
"381": {
"19": {
"id_lot_espace": "381",
"id_lot_objet": "0",
"id_objet_piece": "19",
"params": "",
"label": "Pièce principale - Tête thermostatique",
"pieceLabel": "Pièce principale",
"objLabel": "Tête thermostatique",
"code": "",
"renommable": "0",
"id_famille": "17",
"reveil_possible": "1",
"id_type_espace": "25",
"principal": "1",
"rights": 1
}
}
}
}
Final Code
try {
JSONObject jObject = new JSONObject(sss.trim());
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
Log.d("vt","output1 "+key);
JSONObject obj1 = jObject.getJSONObject(key);
Iterator<String> it1 = obj1.keys();
while (it1.hasNext()) {
String key1 = it1.next();
Log.d("vt","output2 "+key1);
JSONObject obj2 = obj1.getJSONObject(key1);
Iterator<String> it2 = obj2.keys();
while (it2.hasNext()) {
String key2 = it2.next();
Log.d("vt","output3 "+key2);
final JSONObject obj3 = obj2.getJSONObject(key2);
String pieceLabel = String.valueOf(obj3.get("pieceLabel"));
Log.d("vt","final "+pieceLabel);
}
}
}
}catch (Exception e){
Log.d("vt","error "+e.getMessage());
}
You need to iterate your unstructured json recursively and check every key.
Here is a working example to show you how to achieve what you want to do:
public class Main {
private static List<String> values = new ArrayList();
public static void main(String[] args) {
try {
JSONObject jsonObject = new JSONObject(new String(Files.readAllBytes(Paths.get("test.json"))));
findValues(jsonObject);
values.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void findValues(Object root) {
if (root instanceof JSONObject) {
Iterator<String> keys = ((JSONObject)root).keys();
while (keys.hasNext()) {
String key = keys.next();
if ("pieceLabel".equals(key)) {
values.add(((JSONObject)root).getString(key));
}
else {
Object o = ((JSONObject)root).get(key);
findValues(o);
}
}
}
else if (root instanceof JSONArray) {
for (Object o : (JSONArray)root) {
findValues(o);
}
}
}
}
test.json file contains your example json.
Output is :
Pièce principale
Pièce principale
Change the values and order of keys and see the result.
I passed your json through https://jsoneditoronline.org and did not find any error.
I used json-simple which can be found here:
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1
My example is below with no loops.
public static void main( String[] args ) {
JSONParser parser = new JSONParser();
JSONObject jobj = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(".json"),"UTF-8"));
jobj = (JSONObject) parser.parse(reader);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
JSONObject jobj2 = (JSONObject) jobj.get("object"); // outer object.
JSONObject jobj3 = (JSONObject) jobj2.get("17"); // nested object.
JSONObject jobj4 = (JSONObject) jobj3.get("381"); // nested object.
JSONObject jobj5 = (JSONObject) jobj4.get("19"); // nested object.
System.out.println(jobj5.get("pieceLabel")); // Returns the value to where the specified key is mapped.
JSONArray jsarry = (JSONArray) jobj.get("5"); // Json Array.
JSONArray jsarry2 = (JSONArray) jsarry.get(0); // nested Json Array.
JSONObject nestedjsobj = (JSONObject) jsarry2.get(0); // nested object.
System.out.println(nestedjsobj.get("pieceLabel")); // Returns the value to where the specified key is mapped.
}
output:
Pièce principale
Pièce principale
This is my code
List<Object[]> list = query.list();
List<JSONObject> result = new ArrayList<>();
for (Object[] rows : list) {
String buildingId = rows[0].toString();
String floorId = rows[1].toString();
String routerId = rows[2].toString();
String routerName = rows[3].toString();
Map<String, List<String>> floorMap = buildingMap.get(buildingId);
if(floorMap == null) {
floorMap = new HashMap<>();
}
......
}
What i need JSON format is like this
"buildings":{
"building_id":"3"={
"floor_id":"21"=[
"router_id":"3"
]
},
"building_id":"2"={
"floor_id":"20"=[
"router_id":"1101",
"router_id":"1102",
"router_id":"0",
"router_id":"1104",
"router_id":"1106"
],
"floor_id":"17"=[
"router_id":"1111",
"router_id":"1112",
"router_id":"1113"
]
},
"building_id":"1"={
"floor_id":"10"=[
"router_id":"1"
]
}
}
But now i'm getting like this
{
3={
21=[
3
]
},
2={
20=[
1101,
1102,
0,
1104,
1106
],
17=[
1111,
1112,
1113,
]
},
1={
10=[
1
]
}
}
thanks in advance
List<Object[]> list = query.list();
Gson gson = new Gson();
// convert your list to json
String jsonList = gson.toJson(list);
you need Gson Jar and simply you can convert list into json string.
My senior gave this code and finally it worked for me
`#Override
public String getFullRouterList() throws Exception {
//Format
// -- building map with building_id and floor map
// -- floor map with floor_id and list of routers
Map<String, Map<String, List<String>>> buildingMap = new HashMap<>();
System.out.println("in dao of getFullRouterList ");
session = sessionFactory.openSession();
tx = session.beginTransaction();
String sql = "SELECT building_id, floor_id, router_id, router_name FROM iot_trackbit.router_details";
SQLQuery query = session.createSQLQuery(sql);
List<Object[]> list = query.list();
List<JSONArray> result = new ArrayList<>();
for (Object[] rows : list) {
String buildingId = rows[0].toString();
String floorId = rows[1].toString();
String routerId = rows[2].toString();
String routerName = rows[3].toString();
Map<String, List<String>> floorMap = buildingMap.get(buildingId);
if(floorMap == null) {
floorMap = new HashMap<>();
}
List<String> routerList = floorMap.get(floorId);
if(routerList == null) {
routerList = new ArrayList<>();
}
routerList.add(routerId);
floorMap.put(floorId, routerList);
buildingMap.put(buildingId, floorMap);
System.out.println(buildingMap.keySet());
System.out.println(buildingMap);
}
JSONObject finalObj = new JSONObject();
JSONArray buildingsArr = new JSONArray();
for(String buildingId : buildingMap.keySet()) {
JSONObject buildingObject = new JSONObject();
Map<String, List<String>> floorMap = (HashMap<String, List<String>>) buildingMap.get(buildingId);
//{"1":["router1","router2","router3"]}
JSONArray floorsArr = new JSONArray();
for(String floorId : floorMap.keySet()) {
JSONObject floorObject = new JSONObject();
List<String> routerList = floorMap.get(floorId);
//["router1","router2"]
JSONArray array = new JSONArray();
for(String routerId : routerList) {
JSONObject routerObj = new JSONObject();
routerObj.put("id",routerId);
array.add(routerObj);
}
floorObject.put("id",floorId);
floorObject.put("routers", array);
floorsArr.add(floorObject);
}
buildingObject.put("id", buildingId);
buildingObject.put("floors", floorsArr);//floors array
buildingsArr.add(buildingObject);
finalObj.put("buildings",buildingsArr);
}
System.out.println("finalObj.toJSONString() : " +finalObj.toJSONString());
tx.commit();
session.close();
return finalObj.toJSONString();
}`
Now im geting like this format
{
"buildings": [
{
"id": "3",
"floors": [
{
"id": "21",
"routers": [
{
"id": "3"
}
]
},
{
"id": "23",
"routers": [
{
"id": "0"
},
{
"id": "gateway123"
},
{
"id": "1001"
},
{
"id": "1002"
},
{
"id": "1003"
}
]
}
]
},
{
"id": "2",
"floors": [
{
"id": "20",
"routers": [
{
"id": "1101"
},
{
"id": "1102"
},
{
"id": "0"
},
{
"id": "1104"
},
{
"id": "1106"
},
{
"id": "1107"
},
{
"id": "1111"
},
{
"id": "1109"
},
{
"id": "1110"
}
]
},
{
"id": "17",
"routers": [
{
"id": "1111"
},
{
"id": "1112"
},
{
"id": "1113"
},
{
"id": "1114"
},
{
"id": "1115"
},
{
"id": "1116"
},
{
"id": "1117"
},
{
"id": "1118"
},
{
"id": "g1"
},
{
"id": "1119"
},
{
"id": "0"
}
]
},
{
"id": "18",
"routers": [
{
"id": "010101"
},
{
"id": "0"
}
]
}
]
},
{
"id": "1",
"floors": [
{
"id": "10",
"routers": [
{
"id": "1"
}
]
}
]
}
]
}`
Thanks for all
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());
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"));
}
I am having trouble parsing this particular JSONObject,
Here is the object:
{"status":1,"dds":{"id":1,"name":"DDS1","description":"This is DDS 1","children":[{"id":2,"order":1,"type":1,"children":[{"id":3,"order":1,"type":3,"children":[]},{"id":4,"order":2,"type":2,"children":[]}]}]}}
That object is stored in my variable called result, here is my code to parse it:
JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
jsonObj = new JSONObject(result);
jsonArr = jsonObj.getJSONArray("dds");
} catch (JSONException e) {
e.printStackTrace();
}
And it is giving me this error:
org.json.JSONException: Value {"id":1,"children":[{"type":1,"order":1,"id":2,"children":[{"type":3,"order":1,"id":3,"children":[]},{"type":2,"order":2,"id":4,"children":[]}]}],"description":"This is DDS 1","name":"DDS1"} at dds of type org.json.JSONObject cannot be converted to JSONArray
I am trying to break it up into sub arrays of children. Where am I going wrong?
#Mr Love
here is my output to your code
You are calling jsonArr = jsonObj.getJSONArray("dds");, however dds is not an array, it's a JSON object, if you format the JSON you can see it clearly:
{
"status":1,
"dds":{
"id":1,
"name":"DDS1",
"description":"This is DDS 1",
"children":[
{
"id":2,
"order":1,
"type":1,
"children":[
{
"id":3,
"order":1,
"type":3,
"children":[
]
},
{
"id":4,
"order":2,
"type":2,
"children":[
]
}
]
}
]
}
}
So you will just need to call JSONObject dds = jsonObj.getJSONObject("dds"), and if you want the children you would call JSONArray children = jsonObj.getJSONObject("dds").getJSONArray("children");.
private static final String json = "{\"status\":1,\"dds\":{\"id\":1,\"name\":\"DDS1\",\"description\":\"This is DDS 1\",\"children\":[{\"id\":2,\"order\":1,\"type\":1,\"children\":[{\"id\":3,\"order\":1,\"type\":3,\"children\":[]},{\"id\":4,\"order\":2,\"type\":2,\"children\":[]}]}]}}";
public static void main(String[] args) throws JSONException
{
JSONObject jsonObj = new JSONObject(json);
JSONObject dds = jsonObj.getJSONObject("dds");
JSONArray children = dds.getJSONArray("children");
System.out.println("Children:");
System.out.println(children.toString(4));
JSONArray grandChildren = children.getJSONObject(0).getJSONArray("children");
System.out.println("Grandchildren:");
System.out.println(grandChildren.toString(4));
}
Produces:
Children:
[{
"children": [
{
"children": [],
"id": 3,
"order": 1,
"type": 3
},
{
"children": [],
"id": 4,
"order": 2,
"type": 2
}
],
"id": 2,
"order": 1,
"type": 1
}]
Grandchildren:
[
{
"children": [],
"id": 3,
"order": 1,
"type": 3
},
{
"children": [],
"id": 4,
"order": 2,
"type": 2
}
]
You can do it like this, where the JsonElement could be a JSONobject or JsonArray or any primitive type:
private JsonElement findElementsChildren(JsonElement element, String id) {
if(element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if(id.equals(jsonObject.get("id").getAsString())) {
return jsonObject.get("children");
} else {
return findElementsChildren(element.get("children").getAsJsonArray(), id);
}
} else if(element.isJsonArray()) {
JsonArray jsonArray = element.getAsJsonArray();
for (JsonElement childElement : jsonArray) {
JsonElement result = findElementsChildren(childElement, id);
if(result != null) {
return result;
}
}
}
return null;
}