Finding deeply nested key/value in JSON - java

Suppose I have a JSON array like this:
[
{
"id": "429d30a1-9364-4d9a-92e0-a17e00b3afba",
"children": [],
"parentid": "",
"name": "Expo Demo"
},
{
"id": "f80f1034-9110-4349-93d8-a17e00c9c317",
"children":
[
{
"id":"b60f2c1d-368b-42c4-b0b2-a1850073e1fe",
"children":[],
"parentid":"f80f1034-9110-4349-93d8-a17e00c9c317",
"name":"Tank"
}
],
"parentid": "",
"name": "Fishtank"
},
{
"id": "fc8b0697-9406-4bf0-b79c-a185007380b8",
"children": [
{
"id":"5ac52894-4cb6-46c2-a05a-a18500739193",
"children":[
{
"id": "facb264c-0577-4627-94a1-a1850073c270",
"children":[
{
"id":"720472b5-189e-47f1-97a5-a18500a1b7e9",
"children":[],
"parentid":"facb264c-0577-4627-94a1-a1850073c270",
"name":"ubSubSub"
}],
"parentid": "5ac52894-4cb6-46c2-a05a-a18500739193",
"name": "Sub-Sub1"
}],
"parentid":"fc8b0697-9406-4bf0-b79c-a185007380b8", "name":"Sub"
},
{
"id":"4d024610-a39b-49ce-8581-a18500739a75",
"children":[],
"parentid":"fc8b0697-9406-4bf0-b79c-a185007380b8",
"name":"Sub2"
}
],
"parentid": "",
"name": "Herman"
},
{
"id": "a5b140c9-9987-4e6d-a883-a18c00726883",
"children": [
{
"id":"fe103303-fd5e-4cd6-81a0-a18c00733737",
"children":[],
"parentid":"a5b140c9-9987-4e6d-a883-a18c00726883",
"name":"Contains Spaces"
}],
"parentid": "",
"name": "Kiosk"
}
]
No I want to find a certain object based on a id and once I have that, I need its children and all its childrends children
So lets say i want to find the element with an id if 4d024610-a39b-49ce-8581-a18500739a75
That should find the Element Sub2
And now it should produce all the child elements ids witch will be:
facb264c-0577-4627-94a1-a1850073c270
720472b5-189e-47f1-97a5-a18500a1b7e9
Let say I would do
findElementsChildren("4d024610-a39b-49ce-8581-a18500739a75")
So i guess its two parts, first find the "parent" element. Then find its childrends childrends children etc..
Any help would be much appreciated!

You can use recursion to solve the problem of unlimited nesting. With Gson, it would be something like the following code snippet (not tested). Other libraries will provide structures as JsonElement as well.
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;
}

Based on Stefan Jansen's answer I made some changes and this is what I have now:
nestedChildren declared globaly, and before the children are searched reset to new ArrayList()
private void findAllChild(JSONArray array) throws JSONException {
for ( int i=0;i<array.length();i++ ) {
JSONObject json = array.getJSONObject(i);
JSONArray json_array = new JSONArray(json.getString("children"));
nestedChildren.add(json.getString("id"));
if ( json_array.length() > 0 ) {
findAllChild(json_array);
}
}
}
This assumes it is all Arrays, witch in my case it is

Related

How to handle JsonObject to own Object

Now i take JsonObject from API like this:
Its XML object converted to JsonObject.
"Details": {
"row": [
{
"item": [
{
"name": "Account",
"value": 12521512
},
{
"name": "ACCNO",
"value": 4214
},
{
"name": "Number",
"value": 5436
}
]
},
"item": [
{
"name": "Account",
"value": 5789678
},
{
"name": "ACCNO",
"value": 6654
},
{
"name": "Number",
"value": 0675
}
]
},
But i need convert this object and send like this:
{
"Details": {
"row": [
{
"Account": 12521512,
"ACCNO": 4214,
"Number": 12412421
},
{
"Account": 5789678,
"ACCNO": 6654,
"Number": "0675"
}
]
}
}
I have rows more than 1000, i need faster way to handle.
How to handle, please help me
You could use the JSON-java library to parse your input and transform it to your desired format. Something like this works but you may need to adjust it to your needs:
JSONObject jsonObject = new JSONObject(json); // Load your json here
JSONObject result = new JSONObject("{\"Details\": {\"row\": []}}");
for (Object row : jsonObject.getJSONObject("Details").getJSONArray("row")) {
if (!(row instanceof JSONObject)) continue;
Map<Object, Object> values = new HashMap<>();
for (Object item : ((JSONObject) row).getJSONArray("item")) {
if (!(item instanceof JSONObject)) continue;
values.put(((JSONObject) item).get("name"), ((JSONObject) item).get("value"));
}
result.getJSONObject("Details").getJSONArray("row").put(values);
}
// Now result is in your format

Add hashmap having possible serialized JSON values to a JSON string as a node

What is the cheapest way to take the jsonstring and hashmap below and produce the result in JAVA?
pseudocode data example:
String jsonstring = {
"people": {
"name": "name1",
},
"addresses": {
"address1": {
"number": "1234",
"city": "europa"
}
}
}
HashMap hashmap = {
["string.a.1"] = "stringa1",
["string.a.2"] = "stringa2",
["object.a.1"] = "{/"item1/":/"value1/"}" // serialized JSON object
}
String result = {
"people": {
"name": "name1",
},
"addresses": {
"address1": {
"number": "1234",
"city": "europa"
}
},
"buffer": {
"string.a.1": "stringa1",
"string.a.2": "stringa2",
"object.a.1": {
"item1": "value1"
}
}
}
Thanks in advance for any help.

How can I make a JSON object, the output will be like this?

I am very new to json, How can I make a JSON object the structure (output string)would be like this? I am using the org.json library.
Is this a json array contians json array?
I have input like this:
111(root)
----222(child of 111)
--------333(child of 222)
--------444(child of 222)
----123(child of 111)
--------456(child of 123)
--------456(child of 123)
How can I make a json the output would be like blow,
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"value": 3938
},
{
"name": "CommunityStructure",
"value": 3812
}
]
},
{
"name": "graph",
"children": [
{
"name": "BetweennessCentrality",
"value": 3534
},
{
"name": "LinkDistance",
"value": 5731
}
]
}
]
},
{
"name": "animate",
"children": [
{
"name": "Easing",
"value": 17010
},
{
"name": "FunctionSequence",
"value": 5842
}
]
}
]
}
Thanks for you help!
You can change your dependency and use a library that allows Object mapping such as Jackson, or you can do the mapping by hand as follows:
private static JSONObject toJSONObject(String name, Object value) {
JSONObject ret = new JSONObject();
ret.put("name", name);
if (value != null) {
ret.put("value", value);
}
return ret;
}
public static JSONObject addChildren(JSONObject parent, JSONObject... children) {
parent.put("children", Arrays.asList(children));
return parent;
}
public static void main(String[] sargs) {
JSONObject flare = toJSONObject("flare", null);
addChildren(flare,
addChildren(toJSONObject("analytics", null),
addChildren(toJSONObject("cluster", null),
toJSONObject("AgglomerativeCluster", 3938),
toJSONObject("CommunityStructure", 3812)
),
addChildren(toJSONObject("graph", null),
toJSONObject("BetweennessCentrality", 3534),
toJSONObject("LinkDistance", 5731)
)
),
addChildren(toJSONObject("animate", null),
toJSONObject("Easing", 17010),
toJSONObject("FunctionSequence", 5842)
)
);
System.out.println(flare.toString());
}
You can simply have class like this.
public class Node {
String name;
List<Node> children;
String value;
}
This can be achieved by ObjectMapper's pretty print.
public String pretty(Object object) throws JsonProcessingException {
return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}
You may use my library for it.
<dependency>
<artifactId>json-utils</artifactId>
<groupId>org.bitbucket.swattu</groupId>
<version>1.0.16</version>
</dependency>
new JsonUtil().pretty(object);

Parsing Json array from webservice to android

I am trying to parse this json data from web service to android using volley.
This is the json array to be parsed.
[
{
"id":"1",
"conf_room_name":"Tadoba"
},
{
"id":"2",
"conf_room_name":"Melghat"
},
{
"id":"3",
"conf_room_name":"Ranthambore"
},
{
"id":"4",
"conf_room_name":"Corbett"
},
{
"id":"5",
"conf_room_name":"Pench"
}
]
[
{
"id":"1",
"area":"Mafatlal"
},
{
"id":"2",
"area":"Andheri"
}
]
[
{
"id":"1",
"type":"Is Personal"
},
{
"id":"2",
"type":"Meeting"
}
]
I am using this code to get the value out of my json array object ot different arraylists.
RequestQueue requestQueue2= Volley.newRequestQueue(this);
// RequestQueue requestQueue3= Volley.newRequestQueue(this);
// Create json array request
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST,"http://170.241.241.198/test.php",new Response.Listener<JSONArray>(){
public void onResponse(JSONArray jsonArray){
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArray_conf.add(jsonObject.getString("conf_room_name"));
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Error", "Unable to parse json array");
}
});
requestQueue2.add(jsonArrayRequest);
Only 1st array is being filled properly not the other one. I get outofboundsindex exception whenever i try using values from my 2nd arraylist.
All this happens on a button click only i want this to happen when i load my page.
Any help will be appreciated.
Make JSON as Array as below:
[
[
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
[
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
[
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
]
Or Object (easier to reading and understanding):
{
"rooms": [
{
"id": "1",
"conf_room_name": "Tadoba"
},
{
"id": "2",
"conf_room_name": "Melghat"
},
{
"id": "3",
"conf_room_name": "Ranthambore"
},
{
"id": "4",
"conf_room_name": "Corbett"
},
{
"id": "5",
"conf_room_name": "Pench"
}
],
"areas": [
{
"id": "1",
"area": "Mafatlal"
},
{
"id": "2",
"area": "Andheri"
}
],
"types": [
{
"id": "1",
"type": "Is Personal"
},
{
"id": "2",
"type": "Meeting"
}
]
}
PHP code maybe like below:
<?php
$sqlroom = mysql_query("SELECT * FROM `room_table`");
$room_rows = array();
while($r = mysql_fetch_assoc($sqlroom)) {
$room_rows[] = $r;
}
$sqlarea = mysql_query("SELECT * FROM `area_table`");
$area_rows = array();
while($r = mysql_fetch_assoc($sqlarea)) {
$area_rows[] = $r;
}
$sqltype = mysql_query("SELECT * FROM `type_table`");
$type_rows = array();
while($r = mysql_fetch_assoc($sqltype)) {
$type_rows[] = $r;
}
$result = array();
$result["rooms"] = $room_rows;
$result["areas"] = $area_rows;
$result["types"] = $type_rows;
echo json_encode($result);
?>
You seem to be trying to parse three different types of data: conference rooms, areas (which presumably contain conference rooms?) and some information about either one (although it's not clear which). It therefore doesn't make sense to try and store these in a single array as each element contains a different data structure compared to the other two.
If the type is a description of one of the other two objects then it should be compassed within that object, not treated as a separate one. A room doesn't necessarily have to sit within an area but it might also make sense to have it there.
You say you are "pulling all these values from a mysql server and then using php to encode the json data which gives me the structure of the json array" which implies you do not have direct access to the JSON structure, but you should still have access to the PHP structure. The JSON encoder will use the design of the PHP array / object to structure the JSON so, for this to work you need to create more-or-less matching PHP and Java objects at either end of the serialization process.
For instance:
$obj = (object) array
('id' => '1', 'area' => 'Mafatlal', 'rooms' => array
('id' => '1', 'conf_room_name' => 'Tadoba', 'type' => 'Is Personal'),
...
('id' => '2', 'area' => 'Andheri', 'rooms' => array...
);
and
public class Area {
private int id;
private String area;
private Room[] rooms;
}
public class Room {
private int id;
private String conf_room_name;
private String type;
}
Note that, in contrast to the usual Java camel-case naming convention, object variables will usually have to match the incoming JSON variable name (i.e.: conf_room_name instead of confRoomName).
You need to add values using for loop.
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.toString.contains("conf_room_name"))
stringArray_conf.add(jsonObject.getString("conf_room_name"));
else if(jsonObject.toString.contains("area"))
stringArray_area.add(jsonObject.getString("area"));
} catch (JSONException e) {
e.printStackTrace();
}
}

how to parse this in android with json

I want to parse this json in android. Can you help me how to parse, if i need to start from head to parse or from results for this I don't know. Can you help me
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Now, to get the "values", you'll need to do this.
JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i = 0; i < bindings.length(); i++) {
JSONObject binding = bindings.getJSONObject(i);
JSONObject city = binding.getJSONObject("city");
// Get value in city
String cityValue = city.getString("value");
Log.d("CITY", cityValue);
JSONObject country = binding.getJSONObject("country");
// Get value in country
String countryValue = country.getString("value");
Log.d("COUNTRY", countryValue);
}

Categories