I have the following json structure:
"interpretation": {
"ComplexSearchRequest": {
"BoostLanguage": 0,
"Clauses": {
"MustClauses": [
{
"Match": {
"Attribute": "Channel",
"Operator": "None",
"Value": "n twenty four c h"
}
}
],
"MustNotClauses": []
},
"FilterLanguages": [],
"ItemFilters": [],
"MaxResults": 10
},
"GraphManagerRequestId": "baf28b69-0806-4725-9fb4-1d2acd1944ea",
"GraphManagerRequestLanguage": "de",
"Type": "Search"
},
How do I extract the entire node "Clauses" and convert it as string? The output should be:
"Clauses": {
"MustClauses": [
{
"Match": {
"Attribute": "Channel",
"Operator": "None",
"Value": "n twenty four c h"
}
}
],
"MustNotClauses": []
},
An optimal solution is needed.
For simple parsing I use JsonReader.
Let's say you have JSONObject with name interpretation, then following is the simple way to get Clauses:
JSONObject complexSearchRequest = interpretation.getJSONObject("ComplexSearchRequest");
JSONObject clauses = complexSearchRequest.getJSONObject("Clauses");
Log.d("clauses",clauses.toString());
Try using org.json. It's the best I've seen: https://mvnrepository.com/artifact/org.json/json
import org.json.JSONException;
import org.json.JSONObject;
public class JsonSample
{
public static void main(String[] args) throws JSONException
{
String json = "{ \"interpretation\": { \"ComplexSearchRequest\": { \"BoostLanguage\": 0, \"Clauses\": { \"MustClauses\": [ { \"Match\": { \"Attribute\": \"Channel\", \"Operator\": \"None\", \"Value\": \"n twenty four c h\" } } ], \"MustNotClauses\": [] }, \"FilterLanguages\": [], \"ItemFilters\": [], \"MaxResults\": 10 }, \"GraphManagerRequestId\": \"baf28b69-0806-4725-9fb4-1d2acd1944ea\", \"GraphManagerRequestLanguage\": \"de\", \"Type\": \"Search\" }}";
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject.getJSONObject("interpretation").getJSONObject("ComplexSearchRequest").getString("Clauses"));
}
}
Related
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.
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);
I have the following scenario
"sections": [
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
{"num": 2}
],
I'm using JSONArray and JSONObject. Is there some way to do this?
"sections": [
"num": 2,
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
],
I believe you are trying to count the array within. I think you can do it below way.
{
"sections": [{
"id": "XXXX",
"tipology": "TIPOLOGY"
},
{
"id": "XXXX",
"tipology": "TIPOLOGY"
}
],
"num": 2
}
OR
{
"sections": [{
"id": "XXXX",
"tipology": "TIPOLOGY"
},
{
"id": "XXXX",
"tipology": "TIPOLOGY"
}, {
"id": "COUNT",
"num": 2
}
]
}
You can have the json object in the following format, hope it works for you.
{
"sections": {
"num": 100,
"values": [{
"id": "XXXX",
"tipology": "TIPOLOGY"
}]
}
}
And the java code for the above program is below.
import org.json.*;
class test {
public static void main(String[] args) throws JSONException {
JSONObject sections = new JSONObject();
JSONObject obj = new JSONObject();
obj.put("num", new Integer(2));
JSONArray array = new JSONArray();
JSONObject value = new JSONObject();
value.put("id", "XXXX");
value.put("tipology", "TIPOLOGY");
array.put(value);
obj.put("values", array);
sections.put("sections", obj);
System.out.print(sections);
}
}
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);
}
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