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