I want to basically merge data from several json files into one final json file.
The following stripped down version of the code searches for a property, let's say 'label' and updates its value 'new_value'.
This works so far.
But what I need now, is a new property within the node, where the search succeeds.
So basically a new property under 'label' named 'label_new' with value to 'new_value'.
Here is a basic recursive implementation. I know that I need to replace somehow, but every attempt I tried did not work.
Any suggestion that may help?
-Thx
Java:
private static Object k = null;
private static Object v = null;
private static Object parent = null;
public static void iterate(Object obj, JSONObject props, String search) throws Exception {
try {
if (obj instanceof JSONObject) {
parent = obj;
for (Iterator it = ((JSONObject) obj).keys(); it.hasNext();) {
k = it.next();
v = ((JSONObject) obj).get((String) k);
iterate(v, props, search);
}
}
if (obj instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) obj).length(); i++) {
v = ((JSONArray) obj).get(i);
iterate(v, props, search);
}
}
if (obj instanceof String) {
if (k.toString().equalsIgnoreCase(search)) {
((JSONObject) parent).put(search, "NEW_VALUE");
// ((JSONObject) parent).put(search + "_new", "NEW_VALUE");
}
}
} finally {
}
The starting json:
{
"data": {
"group": {
"subGroup": {
"boolean": {
"name": "test",
"description": "test",
"label": "new_value"
},
"description": "test",
"label": "test",
"text": {
"name": "test",
"description": "test",
"label": "new_value"
}
},
"name": "test",
"description": "test",
"label": "test"
}
}
}
The final output I need:
{
"data": {
"group": {
"subGroup": {
"boolean": {
"name": "test",
"description": "test",
"label": "new_value",
"label_new": "new_value"
},
"description": "test",
"label": "test",
"text": {
"name": "test",
"label": "new_value",
"label_new": "new_value"
}
},
"name": "test",
"description": "test",
"label": "new_value",
"label_new": "new_value"
}
}
}
UPDATE:
private static Object k = null;
private static Object v = null;
public static void iterate(Object obj, Object parent, JSONObject props, String search) throws Exception {
try {
if (obj instanceof JSONObject) {
for (Iterator it = ((JSONObject) obj).keys(); it.hasNext();) {
k = it.next();
v = ((JSONObject) obj).get((String) k);
iterate(v, obj, props, search);
}
}
if (obj instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) obj).length(); i++) {
v = ((JSONArray) obj).get(i);
iterate(v, obj, props, search);
}
}
if (obj instanceof String) {
if (k.toString().equalsIgnoreCase(search)) {
// ((JSONObject) parent).put(search, "TEST_A_NEW_VALUE");
((JSONObject) parent).put(search + "_new", "TEST_A_NEW_VALUE");
}
}
} catch (Exception ex) { // throws ConcurrentModificationException
ex.getMessage();
} finally {
}
} // iterate
The Starting json:
{
"data": {
"group": {
"subGroup": {
"boolean": {
"name": "test",
"description": "test",
"label": "test"
},
"description": "test",
"label": "test",
"text": {
"name": "test",
"description": "test",
"label": "test"
},
"choice": {
"name": "test",
"description": "test",
"label": "test",
"items": {
"item": [
{
"label": "test"
},
{
"label": "test"
},
{
"label": "test"
}
]
}
}
},
"name": "test",
"description": "test",
"label": "test"
}
}
}
The current output. While iterating, I get an ConcurrentModificationException.
label within item is not updated. But that is want I want.
{
"data": {
"group": {
"subGroup": {
"description": "test",
"label": "test",
"choice": {
"name": "test",
"description": "test",
"label": "test",
"items": {
"item": [
{
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
},
{
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
},
{
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
}
]
}
},
"label_new": "TEST_A_NEW_VALUE"
},
"name": "test",
"description": "test",
"label": "test",
"label_new": "TEST_A_NEW_VALUE"
}
}
}
First, pass parent as a parameter, it makes more sense, and having it as a global variable may be prone to errors.
Second, to avoid concurrent modification, insert the new key after traversing the object:
if (obj instanceof JSONObject) {
boolean found = false;
for (Iterator it = ((JSONObject) obj).keys(); it.hasNext();) {
k = it.next();
v = ((JSONObject) obj).get((String) k);
if (v instanceof JSONArray || v instanceof JSONObject) {
iterate(v, obj, props, search); // second parameter is the parent
} else if (v instanceof String) {
if (!found && search.equalsIgnoreCase(v)) {
found = true;
}
}
}
if (found) {
// insert 'new' entry
}
}
Related
{ "records": [ { "id": "rec43JpMrSsSmAoGG", "createdTime": "2022-12-17T15:30:47.000Z", "fields": { "Name": "green." } }, { "id": "recBfJzGGNdwRiCWR", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "yellow." } }, { "id": "recDynbN2dibdMLvO", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "purple." } }, { "id": "recNZMK3mZda33CXU", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "brown." } }, { "id": "reca6MBTrUKQXqcIl", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "pink." } }, { "id": "recdM8t7quScDwRLF", "createdTime": "2022-12-17T15:31:16.000Z", "fields": { "Name": "orange." } }, { "id": "recq5aeM3M7Gjsif9", "createdTime": "2022-12-17T15:30:47.000Z", "fields": { "Name": "blue." } }, { "id": "recxcNttZ5UoamShI", "createdTime": "2022-12-17T15:30:47.000Z", "fields": { "Name": "red." } } ] }
its my Json file but i hew to use Volley laibery but ex. Not a primitive array: class org.json.JSONArray
help us
java code is
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://loclhost:1111/json";
JsonObjectRequest jsonArryRequest =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = new JSONArray(response.getJSONArray("records").getJSONObject(1));
} catch (JSONException e) {
e.printStackTrace();
Log.d("Papa","Ex - "+e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorm = error.getMessage();
Log.d("papa", "error : "+errorm);
}
});
queue.add(jsonArryRequest);
You are initializing a new jsonArray that's not the way to do it
Instead of this
JSONArray jsonArray = new JSONArray(response.getJSONArray("records").getJSONObject(1));
Do this
JSONArray jsonArray = response.getJSONArray("records");
JSONObject jsonObject = jsonArray.getJSONObject(1));
By doing it this way you will also get your second json object into jsonObject variable
I want to return a group of groups to n times in the following ways;
[
{
"field": "TestContacts_CompanyName",
"value": "MC 1",
"hasSubgroups": true,
"items": [
{
"field": "TestContacts_ID",
"value": "25",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "25",
"TestContacts_CompanyName": "MC 1"
}
]
},
{
"field": "TestContacts_ID",
"value": "26",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "26",
"TestContacts_CompanyName": "MC 1"
}
]
},
{
"field": "TestContacts_ID",
"value": "27",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "27",
"TestContacts_CompanyName": "MC 1"
}
]
}
]
},
{
"field": "TestContacts_CompanyName",
"value": "MC 2",
"hasSubgroups": true,
"items": [
{ "field": "TestContacts_ID",
"value": "28",
"hasSubgroups": false,
"items": [
{
"TestContacts_ID": "28",
"TestContacts_CompanyName": "MC 2"
}
]
}
]
}
]
I don't want to use collectors.groupingby
public static JSONArray groupedArray(ArrayList<String> groupField,JSONArray itemsArray) throws Exception {
JSONArray itemArrayTemp = new JSONArray();
int i=0;
for (Map.Entry<String,ArrayList<Object>> entry : SLQUtil.groupData(groupField.get(i),itemsArray).entrySet()) {
JSONObject itemTemp = new JSONObject();
itemTemp.put("field",groupField.get(i) );
itemTemp.put("value",entry.getKey() );
if((groupField.size()-i ==1)){
itemTemp.put("hasSubgroups",false );//Single level grouping
itemTemp.put("items",entry.getValue() );
}else if((groupField.size()-i > 1)){
itemTemp.put("hasSubgroups",true );//2nd level grouping
JSONArray jsArray2 = new JSONArray(entry.getValue());//converting array list to json array
JSONArray itemArrayTemp2 = new JSONArray();
for (Map.Entry<String,ArrayList<Object>> entry2 : SLQUtil.groupData(groupField.get(i+1),jsArray2).entrySet()) {
JSONObject itemTemp2 = new JSONObject();
itemTemp2.put("field",groupField.get(i+1));
itemTemp2.put("value",entry2.getKey() );
itemTemp2.put("hasSubgroups",false );
itemTemp2.put("items",entry2.getValue() );
itemArrayTemp2.put(itemTemp2 );//2nd level of grouped data
}
itemTemp.put("items",itemArrayTemp2 );
}
itemArrayTemp.put(itemTemp);//1st level of grouped data
}
return itemArrayTemp;
}
public static Map<String, ArrayList<Object>> groupData(String field,JSONArray itemsArray) throws Exception {
Map<String, ArrayList<Object>> itemMap = new LinkedHashMap<>();
for (int i=0;i<itemsArray.length();i++){
JSONObject itemTemp = itemsArray.getJSONObject(i);
if(!itemMap.containsKey(itemTemp.getString(field))){
itemMap.put(itemTemp.getString(field), new ArrayList<>());
}
itemMap.get(itemTemp.getString(field)).add(itemTemp);
}
return itemMap;
}
public static Map<String, Object> groupDataRecursive(String currentKey, Map<String, Object> map, Map<String, Object> out) throws SQLException, Exception {
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
groupDataRecursive(currentKey, (Map<String, Object>) entry.getValue(), out);
} else {
Map tempMap = SLQUtil.groupData(currentKey,(JSONArray)entry.getValue());
map.put( entry.getKey(),tempMap);
//out.put(currentKey + "." + entry.getKey(), entry.getValue());
}
}
return map;
}
Data.json:
{"UniversalWord": {"UniversalWord": [
{
"uw_id": 1,
"HeadWord": {"word": "aare"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aare"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
},
{
"uw_id": 2,
"HeadWord": {"word": "aarhus"},
"Restriction": {"SemanticRelations": {"feat": [
{
"att": "restriction_type",
"value": "iof"
},
{
"att": "target",
"val": " "
},
{
"att": "restriction_type",
"value": "equ"
},
{
"att": "target",
"val": " "
}
]}},
"NLDescription": {
"Gloss": {"feat": {
"att": "Description",
"val": "\"PORT CITY OF DENMARK IN EASTERN JUTLAND\""
}},
"Lemma": {"feat": {
"att": "word",
"val": "aarhus"
}},
"Example": {"feat": {
"att": "description",
"val": "\"\""
}}
},
"MetaInfo": {
"Frequency": {"freq": ""},
"UWSource": {"Source_id": "WORDNET"}
}
}
]}}
Required output:
Word Searched: aare
uwid = 1
headword = aare
semantic relation value = iof
target = ""
gloss = A RIVER IN NORTH CENTRAL SWITZERLAND THAT RUNS NORTHEAST INTO THE RHINE
lemma = aare
example = ""
frequency = ""
Source_ID = wordnet
code.java
public class SearchJson
{
public void SearchValueInJson(StringBuilder sb)
{
try
{
String jsonData = sb.toString();
JSONObject jobj = new JSONObject(jsonData);
Map<String,String> map = new HashMap<String,String>();
iterateJson(jobj,map);
System.out.println(map.toString());
}
catch(Exception e)
{
System.out.println(e);
}
}
public void iterateJson(JSONObject jobj,Map map)
{
for(Object o : jobj.keySet())
{
if(jobj.get(o.toString())instanceof JSONObject)
iterateJson(jobj.getJSONObject(o.toString()),map);
else
map.put(o.toString(), jobj.get(o.toString()));
}
}
}
this code i tried but it is not giving me expected output.
How to retrieve this information from the json file? I'm not getting the proper solution for it. Please give code for this. And assume that you don't know key values of data on that basis have to retrieve.
Check the below code snippet, this may solve your problem.
JSONObject jobj = new JSONObject(jsonData);
JSONArray arr = jobj.getJSONObject("UniversalWord").getJSONArray("UniversalWord");
for (int i = 0; i < arr.length(); i++)
{
String uw_id = arr.getJSONObject(i).getString("uw_id");
System.out.println(uw_id);
String headWord = arr.getJSONObject(i).getJSONObject("HeadWord").getString("word");
System.out.println(headWord);
String nLDescription = arr.getJSONObject(i).getJSONObject("NLDescription").getJSONObject("Gloss").getJSONObject("feat").getString("val");
System.out.println(nLDescription);
}
I'm having trouble trying to access certain values in a JSON file.
The file has multiple objects stored inside an array.
The value I need to return is "60" inside the "maxspeed" string.
When the current code is executed in debug it just remains in a loop.*Not sure why)
The value of the "result" string is the entire json file.
Would anyone be able to explain how to access this value?
Thanks.
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T00:27:03Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}
Code:
protected Void doInBackground(String... params) {
android.os.Debug.waitForDebugger();
//String url_select = "http://yoururlhere.com";
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(encode2);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line); } }
else {
Log.e("==>", "Failed to download file"); }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
result = builder.toString();
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
JSONObject maxspeed = parentObject.getJSONObject("maxspeed");
System.out.print(""+maxspeed.toString()+"\n");
//String[] elementNames = JSONObject.(speedJSON);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", speedJSON.length());
for (int i = 0; i< speedJSON.length(); i++)
{
String value = speedJSON.getString(i);
System.out.printf("name=%s, value=%s\n", speedJSON.get(i), value);
}
//And then read attributes like
/* for(int i = 0; i<speedJSON.length(); i++){
JSONObject child = speedJSON.getJSONObject(i);
if(child.getString("type").equals("way")){
JSONObject tag = speedJSON.getJSONObject(i);
JSONObject maxspeed = tag.getJSONObject("tags");
String speed = maxspeed.getString("maxspeed");
txtSpeed.setText(speed);
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String speedLimit = jObject.getString("maxspeed");
txtSpeed.setText(speedLimit);
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
*/ } // protected void onPostExecute(Void v)
}
Okay your first problem is that not all JSONObjects from your "elements" array have a max speed property. The second problem is that you are not iterating over your JSONArray correctly.
Lets start with the second proble:
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
}
Now your element is the JSONObject which contains your different properties (type, id, lon, ...)
To solve your first problem you can check if a JSONObject contains the key you are looking for (maxspeed)
if (!element.isNull("tags") {
JSONObject tags = (JSONObject)element.get("tags");
if (!tags.isNull("maxspeed") {
String maxspeed = tags.getString("maxspeed");
}
} else {
//Your error handling here...
}
Hope this helps!
I have a complex JSON as below which I need to parser recursively. The end result of recursion is Map> type of object where key is the audience - name value and the inner map is Text-key, Title-value.
This is just a part of the complete JSON.
"sections": {
"1": {
"1": {
"1": {
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
},
"styleHint": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
}
}
},
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
},
"styleHint": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
}
}
},
"2": {
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
},
"styleHint": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
}
}
},
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
},
"2": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
},
"styleHint": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
}
}
},
"2": {
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
},
"styleHint": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
}
},
"anchor":"xxx"
},
"3": {
"1": {
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"tag": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
},
"styleHint": {
"tag": {
"name": "xxx",
"title": "xxx",
"id": "xxx"
}
}
}
},
"title": "xxx",
"text": "xxx",
"tags": {
"audience": {
"1": {
"name": "xxx",
"title": "xxx",
"id": "xxxx"
}
},
"styleHint": {
"1": {
"name": "xx",
"title": "xxx",
"id": "xxxx"
}
}
}
}
}
I used JSONObject for this only to realise very late that iteration happens in reverse order :(
I tried to parse the whole structure recursively and reverse it to my benefit. BUt the order is going haywire :( :( mainly because of the text, title, snippet which follows the 2nd text,title and has 2 audience names. The text and title of that part get skipped due to which the whole order is compromised
Please help !! my current implementation is as below
private Map<String, Map<String, String>> parseTextAndTitle(JSONObject json,
Map<String, Map<String, String>> ttMap, String article,
List<String> usrGrp) throws JSONException {
logger.info("Entering method..");
String userGroup = null;
Map<String, String> titleAndText = new LinkedHashMap<String, String>();
Map<String, String> currMap = new LinkedHashMap<String, String>();
Map<String, String> tempMap = new LinkedHashMap<String, String>();
Iterator<String> keys = json.sortedKeys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject value = null;String firstKey = null;
String text = null;String title = null;
int length = 0;
try {
value = json.getJSONObject(key);
if (key.equalsIgnoreCase(STYLEHINT) || key.equalsIgnoreCase(ANCHOR)
|| key.equalsIgnoreCase(INLINE)) {
continue;
}
if (key.equals(TEXT)) {
text = json.getString(key);
text = removeHtmlTag(text);
logger.debug("TEXT RETRIEVED:" + text);
if(text != null) {
titleAndText.put(text, "");
}
else
logger.debug("Text not retrieved!!");
}
if (key.equals(TITLE)) {
title = json.getString(TITLE);
title = appendNewline(title);
logger.debug("TITLE RETRIEVED:" + title);
if (title != null) {
for (Map.Entry<String, String> iter : titleAndText
.entrySet())
firstKey = iter.getKey();
if(firstKey != null) {
titleAndText.put(firstKey, title);
}
else
logger.debug("NO key present in textAndTitle Map!!");
}
}
if (key.equals(AUDIENCE_TAG)) {
try {
length = value.length();
for (int i = 0; i < length; i++) {
userGroup = (String) value.getJSONObject(
String.valueOf(i + 1)).get(NAME);
logger.debug("USERGROUP RETRIEVED:" + userGroup);
usrGrp.add(userGroup);
}
} catch (Exception e) {
userGroup = (String) value.getJSONObject(TAG).get(NAME);
logger.debug("USERGROUP RETRIEVED:" + userGroup);
usrGrp.add(userGroup);
}
}
else{
parseTextAndTitle(value, ttMap, article, usrGrp);
}
} catch (Exception e) {
logger.debug("value not a JSON Object..rather an element");
// Extract the text values
if (key.equals(TEXT)) {
text = json.getString(key);
text = removeHtmlTag(text);
logger.debug("TEXT RETRIEVED:" + text);
if(text != null) {
titleAndText.put(text, "");
}
else
logger.debug("Text not retrieved!!");
}
if (key.equals(TITLE)) {
title = json.getString(TITLE);
title = appendNewline(title);
logger.debug("TITLE RETRIEVED:" + title);
if (title != null) {
for (Map.Entry<String, String> iter : titleAndText
.entrySet())
firstKey = iter.getKey();
if(firstKey != null) {
titleAndText.put(firstKey, title);
}
else
logger.debug("NO key present in textAndTitle Map!!");
}
}
}
if (!(usrGrp.isEmpty()) && !(titleAndText.isEmpty())
&& title != null) {
if(usrGrp.size() > 1)
{
for(int i=0;i<usrGrp.size();i++)
{
//If user group already present, extract current text,title map
//If not put usergroup as key, text,title map as value
if (ttMap.containsKey(usrGrp.get(i))) {
currMap = ttMap.get(usrGrp.get(i));
if (currMap.isEmpty()) {
ttMap.put(usrGrp.get(i), titleAndText);
} else {
currMap = ttMap.get(usrGrp.get(i));
for (Map.Entry<String, String> entry : currMap
.entrySet()) {
tempMap.put(entry.getKey(),
(String) entry.getValue());
}
for (Map.Entry<String, String> ttEntry : titleAndText
.entrySet()) {
tempMap.put(ttEntry.getKey(),
(String) ttEntry.getValue());
}
ttMap.put(usrGrp.get(i),tempMap);
// titleAndText = new LinkedHashMap<String, String>();
tempMap = new LinkedHashMap<String, String>();
}
}
else {
ttMap.put(usrGrp.get(i), titleAndText);
}
}
titleAndText.clear();
}
else
{
if (ttMap.isEmpty())
{
tempMap = titleAndText;
ttMap.put(usrGrp.get(0), tempMap);
}
else {
currMap = ttMap.get(usrGrp.get(0));
if (currMap.isEmpty()) {
ttMap.put(usrGrp.get(0), titleAndText);
}else {
currMap = ttMap.get(usrGrp.get(0));
for (Map.Entry<String, String> entry : currMap
.entrySet()) {
tempMap.put(entry.getKey(),
(String) entry.getValue());
}
for (Map.Entry<String, String> ttEntry : titleAndText
.entrySet()) {
tempMap.put(ttEntry.getKey(),
(String) ttEntry.getValue());
}
ttMap.put(usrGrp.get(0),tempMap);
titleAndText.clear();
}
}
}
usrGrp.clear();
}
}
logger.info("Exiting method..");
return ttMap;
}
Modified #sklimkovitch code to get it working in some complex Json Structure...
public void loopThroughJson(Object input) throws JSONException {
if (input instanceof JSONObject) {
Iterator<?> keys = ((JSONObject) input).keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (!(((JSONObject) input).get(key) instanceof JSONArray))
if (((JSONObject) input).get(key) instanceof JSONObject) {
loopThroughJson(((JSONObject) input).get(key));
} else
System.out.println(key + "=" + ((JSONObject) input).get(key));
else
loopThroughJson(new JSONArray(((JSONObject) input).get(key).toString()));
}
}
if (input instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) input).length(); i++) {
JSONObject a = ((JSONArray) input).getJSONObject(i);
loopThroughJson(a);
}
}
}
package Test.json;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App {
public static void main(String[] args) {
String str = "{\"a\":\"1\", \"b\":\"2\", \"c\":[{\"d\":\"4\"},{\"e\":\"5\"},{\"f\":[{\"g\":\"6\"},{\"h\":\"7\"}]}], \"i\":8}";
try {
loopThroughJson(new JSONObject(str));
} catch (JSONException e) {
e.printStackTrace();
}
}
public static void loopThroughJson(Object input) throws JSONException {
if (input instanceof JSONObject) {
Iterator<?> keys = ((JSONObject) input).keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (!(((JSONObject) input).get(key) instanceof JSONArray))
System.out.println(key + "=" + ((JSONObject) input).get(key));
else
loopThroughJson(new JSONArray(((JSONObject) input).get(key).toString()));
}
}
if (input instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) input).length(); i++) {
JSONObject a = ((JSONArray) input).getJSONObject(i);
Object key = a.keys().next().toString();
if (!(a.opt(key.toString()) instanceof JSONArray))
System.out.println(key + "=" + a.opt(key.toString()));
else
loopThroughJson(a.opt(key.toString()));
}
}
}
}
Output:
a=1
b=2
d=4
e=5
g=6
h=7
i=8
Instead of
while (keys.hasNext()) {
<blah blah>
if (key.equalsIgnoreCase(STYLEHINT) || key.equalsIgnoreCase(ANCHOR)
|| key.equalsIgnoreCase(INLINE)) {
continue;
}
if (key.equals(TEXT)) {
<blah blah>
}
if (key.equals(TITLE)) {
....
One can simply code:
text = json.getString(TEXT);
<deal with text>
title = json.getString(TITLE);
<etc>
If it's possible that the some of the key values are not there, simply test for their absence with has before fetching them.
Since STYLEHINT, ANCHOR, and INLINE are ignored, simply don't fetch them.
To handle the screwy layout of the JSON, do this:
if (json.has("title")) {
<extract title/text/tags/stylehint as described above>
}
else {
Iterator<String> keys = json.sortedKeys();
while (keys.hasNext()) {
// Note that "key" must be "1", "2", "3"...
String key = keys.next();
value = json.getJSONObject(key);
<recursively call method using "value">
}
}
Found a solution to the ordering..ditched JSONObject API and used gson JsonObject instead
private Map<String, List<String>> parseJsonSection(
Map<String, List<String>> retTextMap, JsonObject jsonObject,
String lastKey, StringBuffer tt, List<String> ttext)
throws ParseException, JSONException {
for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
logger.debug("Key:" + key + "\n" + value.toString());
if (key.equalsIgnoreCase(STYLEHINT) || key.equalsIgnoreCase(INLINE)
|| key.equalsIgnoreCase(ANCHOR))
continue;
if (key.equalsIgnoreCase(TEXT)) {
tt.append(value.toString());
ttext.add(tt.toString());
}
if (key.equalsIgnoreCase(TITLE) && tt.length() == 0) {
tt = new StringBuffer();
tt.append(value.toString() + "-");
}
if (key.equalsIgnoreCase(NAME)) {
logger.debug("Value of usergrp:" + value.toString());
String usrGrp = value.toString();
if (retTextMap.isEmpty()) {
if (tt.toString() != null) {
List<String> temp = new ArrayList<String>();
temp = ttext;
retTextMap.put(usrGrp, temp);
}
return retTextMap;
} else if (retTextMap.get(usrGrp) != null) {
List<String> temp = retTextMap.get(value.toString());
if (!temp.contains(tt.toString()))
temp.add(tt.toString());
retTextMap.put(usrGrp, temp);
} else if (retTextMap.get(usrGrp) == null) {
if (tt != null) {
List<String> temp = new ArrayList<String>();
temp.add(tt.toString());
retTextMap.put(usrGrp, temp);
return retTextMap;
}
}
}
if (value instanceof JsonObject) {
parseJsonSection(retTextMap, (JsonObject) value, key, tt, ttext);
}
}
return retTextMap;
}