How to work with json object and jsonarray - java

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

Related

Insert complex nested JSON into MongoDB using Java

I have a complex and nested JSON File which looks like this
{
"databases": {
"component": "pages/dems/transparency/workspaces/DatasourcesWorkspace.vue",
"children": [
{
"name": "Databases",
"path": "databases",
"component": "pages/dems/transparency/workspaces/Databases.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/databases/databases.html"
},
{
"name": "Schemas",
"path": "schemas",
"component": "containers/EmptyContainer.vue",
"hide": true,
"children": [
{
"name": "",
"component": "pages/dems/transparency/workspaces/Schemas.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/schemas.html"
},
{
"name": "",
"path": "relationship/:id",
"component": "pages/dems/transparency/workspaces/profilecolumn/ViewRelationShip.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/relationship/relationship.html"
}
]
}
]
}
}
I want to insert it into MongoDB. The structure would be like this:
{
"_id":"id1",
"field":"databases",
"value":{
"component": "pages/dems/transparency/workspaces/DatasourcesWorkspace.vue",
"children": [
{
"name": "Databases",
"path": "databases",
"component": "pages/dems/transparency/workspaces/Databases.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/databases/databases.html"
},
{
"children": [
{
"name": "",
"component": "pages/dems/transparency/workspaces/Schemas.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/datasources/databases/schemas.html"
},
{
"name": "",
"path": "relationship/:id",
"component": "pages/dems/transparency/workspaces/profilecolumn/ViewRelationShip.vue",
"hide": true,
"help": "context-sensitive-help/transparency/workspaces/relationship/relationship.html"
}
]
}
]
}
}
I need to also check if any object has the containers/EmptyContainer.vue inside the component value then do not insert that object inside MongoDB.
I have tried many methods but didn't work.
Code tried, which is not working as expected:
public ArrayList<Document> processJsonV4(Object source) throws JSONException {
ArrayList<Document> rootDoc = new ArrayList<>();
if (source instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) source;
Document document = new Document();
if (jsonObject.has("component") && !"containers/EmptyContainer.vue".equals(jsonObject.getString("component"))) {
for (Iterator keys = jsonObject.keys(); keys.hasNext(); ) {
String key = (String) keys.next();
Object value = jsonObject.get(key);
document.append(key, value);
}
} else {
for (Iterator keys = jsonObject.keys(); keys.hasNext(); ) {
String key = (String) keys.next();
Object value = jsonObject.get(key);
processJsonV4(value);
}
}
rootDoc.add(document);
}
KLogger.info("RootDoc: " + rootDoc);
return rootDoc;
}
How can I do this using Java?
A simple recursive way could be to construct and add to the list of Documents when you invoke them:
public void readAndConstructMongoDoc() {
JSONObject jsonData = readFileData("<your-file.json>");
List<Document> rootDoc = new ArrayList<>();
constructRootDoc(rootDoc, jsonData);
// Save in mongo -> rootDoc
}
private void constructRootDoc(List<Document> rootDoc, Object source) {
if (source instanceof JSONObject) {
JSONObject jsonObject = new JSONObject();
if (jsonObject.has("component") && !"containers/EmptyContainer.vue".equals(jsonObject.getString("component"))) {
rootDoc.add(convertToMongoDocument(jsonObject));
JSONArray children = jsonObject.getJSONArray("children");
int length = children.length();
for (int i = 0; i < length; i++) {
// Recursively call for all child node and pass the rootDoc
testJson(rootDoc, children.getJSONObject(i));
}
}
}
}
private Document convertToMongoDocument(JSONObject jsonObject) {
Document document = new Document();
document.append("name", jsonObject.getString("name"));
document.append("path", jsonObject.getString("path"));
document.append("hide", Boolean.valueOf(jsonObject.getString("hide")));
document.append("component", jsonObject.getString("component"));
return document;
}
Side Note: I believe your Mongo Document schema can be improvised and doesn't have to be storing the data in this format.

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

Exception Cast JsonObject

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

Trouble with Parsing JSONObject in java

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

Categories

Resources