How to name a JSON? - java

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

Related

How can I more efficiently find all of targeted objects in JSON File?

I have a JSON file that is serving as data storage for my application:
{
"users": {
"instructors": [
{
"id": 1234,
"password": "hello1234",
"name": "Teacher 1",
"listOfCourses": [
{
"id": 3622,
"name": "CS 3622",
"studentsEnrolled": [
{
"id": 1002,
"name": "Student 1",
"dateOfBirth": "00/11/2222"
},
{
"id": 1002,
"name": "Student 2",
"dateOfBirth": "00/11/2222"
}
]
},
{
"id": 4306,
"name": "CS 4306",
"studentsEnrolled": [
{
"id": 1002,
"name": "Student 3",
"dateOfBirth": "33/44/55"
},
{
"id": 1002,
"name": "Jay Wright",
"dateOfBirth": "33/44/5555"
}
]
}
]
}
],
"admin": [
{
"userId": 12345,
"userPassword": "hello12345",
"name": "Admin 1"
},
{
"userId": 123456,
"userPassword": "hello12345",
"name": "Admin 2"
}
]
}
}
The above file is passed into a Java.io.File object. I am trying to find a more time efficient manner of retrieving all the course objects from the JSON file. I am currently using Jackson and have implemented the below method:
public List<Course> retrieveAll() throws IOException {
if (this.allCourses != null) {
return this.allCourses;
}
List<Course> listOfAllCourses = new ArrayList<>();
JsonNode instructors = root.get("users").get("instructors");
ArrayNode arrayNode = (ArrayNode) instructors;
Iterator<JsonNode> iter = arrayNode.iterator();
while (iter.hasNext()) {
JsonNode currentInstructor = iter.next();
ArrayNode arrayNodeOfCourses = (ArrayNode) currentInstructor.get("listOfCourses");
Iterator<JsonNode> iter2 = arrayNodeOfCourses.iterator();
while (iter2.hasNext()) {
Course currentCourse = objectMapper.treeToValue(iter2.next(), Course.class);
currentCourse.setCourseInstructor(objectMapper.treeToValue(currentInstructor, Instructor.class));
listOfAllCourses.add(currentCourse);
}
}
this.allCourses = listOfAllCourses;
return listOfAllCourses;
}
However, I am looking for a more efficient way of doing this hopefully without nested loops as that can give the method a time efficiency of O(nm).

Compare two json arrays and return common elements java

I am a newbie to java. I have a JSONArray like this
String data1 = "[{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-28T18:37:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-29T18:35:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-30T18:41:00.000Z\"},\"sort\":[1576653361739],\"_score\":null}]";
String data2 = "[ { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-28T18:37:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-29T18:35:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-17T18:35:00.000Z\" }, \"sort\": [ 1576653361736 ], \"_score\": null } ]" ;
JSONArray jsonElement1 = new JSONArray(data1) ;
JSONArray jsonElement2 = new JSONArray(data2) ;
After conversion:
jsonElement1 = [
{"_index":"sales_csv","_source":{"Order Date":"2016-01-28T18:37:00.000Z"},"sort":[1576653361740],"_score":null},
{"_index":"sales_csv","_source":{"Order Date":"2016-01-29T18:35:00.000Z"},"sort":[1576653361740],"_score":null},
{"_index":"sales_csv","_source":{"Order Date":"2016-01-30T18:41:00.000Z"},"sort":[1576653361739],"_score":null}]
jsonElement2 = [
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-28T18:37:00.000Z" }, "sort": [ 1576653361740 ], "_score": null },
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-17T18:35:00.000Z" }, "sort": [ 1576653361736 ], "_score": null },
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-29T18:35:00.000Z" }, "sort": [ 1576653361740 ], "_score": null }, ]
I need to compare both the JSONArray and return the common JSONobjects between both the array and append it to the new JSONarray output
Required Output:
output = [
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-28T18:37:00.000Z" }, "sort": [ 1576653361740 ], "_score": null },
{ "_index": "sales_csv", "_source": { "Order Date": "2016-01-29T18:35:00.000Z" }, "sort": [ 1576653361740 ], "_score": null }
]
I tried this answer Comparing 2 JSONArray. But it returns either true/ false.
Here's the Code I tried:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.util.*;
import static java.lang.System.out;
public class home {
public static JSONArray sortJsonArray(JSONArray inputUnSort, JSONArray outputSort) throws JsonProcessingException {
for (int i = 0; i < inputUnSort.length(); i++) {
ObjectMapper om = new ObjectMapper();
om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
Map<String, Object> map = null;
try {
map = om.readValue(inputUnSort.getJSONObject(i).toString(), HashMap.class);
} catch (IOException e) {
e.printStackTrace();
}
String jsonstr = om.writeValueAsString(map);
JSONObject json = new JSONObject(jsonstr);
outputSort.put(json);
}
return outputSort;
}
public static JSONArray compareJsonArray(JSONArray jsonElement1, JSONArray jsonElement2) throws JsonProcessingException {
// Sorting
JSONArray jsonElement1sort = new JSONArray() ;
JSONArray jsonElement2sort = new JSONArray();
jsonElement1sort = sortJsonArray( jsonElement1, jsonElement1sort);
jsonElement2sort = sortJsonArray( jsonElement2, jsonElement2sort);
JSONArray outputJSONelement = new JSONArray();
for (int i = 0; i < jsonElement1sort.length(); i++){
for (int j = 0; j < jsonElement2sort.length(); j++) {
if (jsonElement1sort.getJSONObject(i).toString().equals(jsonElement2sort.getJSONObject(j).toString())){
outputJSONelement.put(jsonElement1sort.getJSONObject(i));
}
}
}
return outputJSONelement;
}
public static void main(String[] args) throws JsonProcessingException {
String data1 = "[{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-28T18:37:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-29T18:35:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-30T18:41:00.000Z\"},\"sort\":[1576653361739],\"_score\":null}]";
String data2 = "[ { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-28T18:37:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-29T18:35:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-17T18:35:00.000Z\" }, \"sort\": [ 1576653361736 ], \"_score\": null } ]" ;
JSONArray jsonElement1 = new JSONArray(data1) ;
JSONArray jsonElement2 = new JSONArray(data2) ;
out.println(jsonElement1);
out.println(jsonElement2);
out.println(compareJsonArray(jsonElement1, jsonElement2));
}
}
The above code looks huge.
Any shortest way to achieve this
Since you are doing O(N^2) comparison to find the common elements already, you don't need to sort the array before. Just removing the sorting should also work and reduce a good amount of redundant code
Instead of string comparison use JSONObject.similar()

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

Producing a wrong JSON (Data is being repeated for every element)

The Data inside T3 array is being repeated for every element .
This is my program where i am trying to generate the JSON , but i see that the value of T3 array is being repeated for every element
package com;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws JSONException {
Test testJson = new Test();
Map<String, LinkedList<String>> categoryitemslistMap = new LinkedHashMap<String, LinkedList<String>>();
JSONObject mainObject = new JSONObject();
JSONArray T3Array = new JSONArray();
JSONArray T2Array = new JSONArray();
LinkedList<String> T3ValuesList = new LinkedList<String>();
T3ValuesList.add("Bottled");
T3ValuesList.add("Fountain");
categoryitemslistMap.put("Soft Drinks", T3ValuesList);
String t2consildated_Data = "Lemon,Orange";
for (Map.Entry<String, LinkedList<String>> entry : categoryitemslistMap.entrySet()) {
String t1data = entry.getKey();
if (t1data.equalsIgnoreCase("Soft Drinks")) {
LinkedList<String> t1ChildList = entry.getValue();
for (String t2Data : t1ChildList) {
if (t2consildated_Data != null&& !t2consildated_Data.isEmpty()) {
StringTokenizer stt = new StringTokenizer(t2consildated_Data, ",");
while (stt.hasMoreTokens()) {
String t3data = stt.nextToken();
JSONArray leaf = testJson.createLeaf();
JSONObject lemon = new JSONObject().put("name", t3data).put("leaf", new JSONArray().put(leaf));
T3Array.put(lemon);
}
}
JSONObject bottled = new JSONObject().put("name", t2Data).put("T3", T3Array);
T2Array.put(bottled);
}
JSONObject softDrink = new JSONObject().put("T2", T2Array);
JSONObject json = new JSONObject().put(t1data, softDrink);
mainObject.put("items", json);
} // end of processing values of categoryitemslistMap(Linked List)
} // end of processing categoryitemslistMap
System.out.println(mainObject);
} // end of main method
public JSONArray createLeaf() throws JSONException {
JSONArray ja = new JSONArray();
for(int i=0;i<2;i++)
{
if(i==0)
{
JSONObject jo = new JSONObject();
jo.put("name", "500 ML");
ja.put(jo);
}
else if(i==1)
{
JSONObject jo = new JSONObject();
jo.put("name", "1 Litre");
ja.put(jo);
}
}
return ja;
}
}
This is the JSON it is producing
{
"items": {
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
},
{
"name": "Orange",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
},
{
"name": "Lemon",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
},
{
"name": "Orange",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
}
]
},
{
"name": "Fountain",
"T3": [
{
"name": "Lemon",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
},
{
"name": "Orange",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
},
{
"name": "Lemon",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
},
{
"name": "Orange",
"leaf": [
[
{
"name": "500 ML"
},
{
"name": "1 Litre"
}
]
]
}
]
}
]
}
}
}
You need to initialize you T3Array inside the loop that starts with for (String t2Data : t1ChildList) { //.... Otherwise, you will be adding the same objects to the same array twice.

How to read a JSON file in Java using org.json.simple package

I am going to get facebook read_books
The file is in this format:
{
"data": [
{
"id": "270170479804513",
"from": {
"name": "L I",
"id": "1000022"
},
"start_time": "2014-01-22T09:31:00+0000",
"publish_time": "2014-01-22T09:31:00+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "133556360140246",
"url": "https://www.facebook.com/pages/Pride-and-Prejudice/133556360140246",
"type": "books.book",
"title": "Pride and Prejudice"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
},
{
"id": "270170328",
"from": {
"name": "h",
"id": "100004346894022"
},
"start_time": "2014-01-22T09:29:42+0000",
"publish_time": "2014-01-22T09:29:42+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
}
],
I need books titles and their URL. I run the below code but I get Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
while ((inputLine = in.readLine()) != null)
{
s = s + inputLine + "\r\n";
if (s == null) {
break;
}
t = t + inputLine + "\r\n";
}
in.close();
t = t.substring(0, t.length() - 2);
System.out.println(t);
Object dataObj =JSONValue.parse(t);
System.out.println(dataObj);
JSONObject dataJson = (JSONObject) dataObj;
JSONArray data = (JSONArray) dataJson.get("data");
for (Object o: data)
{
JSONObject indata= (JSONObject) o;
Object indatafirst=(JSONObjec`enter code here`t).get("0");
String inndata=(String) indatafirst.get("data");
System.out.println("inndata"+inndata);
}}
but it is not true
The problem is with the following line:
String inndata=(String) indatafirst.get("data");
The data field in the JSON is not a String, it's a nested JSON object.
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
}
This explains your ClassCastException.
Instead you should do something like:
JSONObject data = (JSONObject) indatafirst.get("data");
JSONObject book = (JSONObject) data.get("book");
String bookTitle = book.get("title");

Categories

Resources