I am new to Java. I am fetching data from DB and adding into Hashmap and then the Hashmap data to Array List to obtain JSON data. But I am not getting the output as expected. Child values should be added to the Hashmap based on the parent.
Java code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import com.google.gson.Gson;
public class HaspmapEx
{
public static void main(String[] args)
{
Connection connection = null;
PreparedStatement pst = null;
ResultSet rs = null;
PreparedStatement pst2 = null;
ResultSet rs2 = null;
ArrayList<Object> list = new ArrayList<Object>();
ArrayList<Object> list1 = new ArrayList<Object>();
LinkedHashMap<String, Object> outMap= new LinkedHashMap<String, Object>();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl","REF","REF");
String qstr = "select distinct PARENT_ORG_NAME from demo_org_data";
String qstr1 = "select distinct org_lev1,org_lev2 from demo_org_data";
pst=connection.prepareStatement(qstr);
rs=pst.executeQuery();
pst2 = connection.prepareStatement(qstr1);
rs2 = pst2.executeQuery();
while (rs.next()) {
LinkedHashMap<String, Object> category = new LinkedHashMap<String, Object>();
category.put("label", rs.getString(1));
while (rs2.next())
{
LinkedHashMap<String, Object> category1 = new LinkedHashMap<String, Object>();
LinkedHashMap<String, Object> category2 = new LinkedHashMap<String, Object>();
category1.put("label", rs2.getString(1));
category1.put("label", rs2.getString(2));
category1.put("category", category2);
list1.add(category1);
}
category.put("category",list1);
list.add(category);
}
}
catch (SQLException sql) {
System.out.println("SQLException occurred while fetching the data");
}
catch (Exception e) {
System.out.println("Exception occurred while fetching the data");
}
outMap.put("category", list);
System.out.println(new Gson().toJson(outMap).toString());
}
}
Output for the above Java code :
"category": [{
"label": "CEO",
"category": [{
"label": "CFO",
"category": {
"label": "Payables"
}
}, {
"label": "CFO",
"category": {
"label": "Receivables"
}
}, {
"label": "CIO",
"category": {
"label": "HR"
}
}, {
"label": "CIO",
"category": {
"label": "PR"
}
}, {
"label": "CTO",
"category": {
"label": "Architect"
}
}, {
"label": "CTO",
"category": {
"label": "Project Manager"
}
}, {
"label": "CTO",
"category": {
"label": "QA Manager"
}
}]
}]
}
I want the output as shown below. The Parent-Child relationship can be clearly seen in the JSON data below
"category": [{
"label": "CEO",
"category": [{
"label": "CTO",
"category": [{
"label": "Proj. Manager"
}, {
"label": "Q & A Manager"
}, {
"label": "Architect"
}]
}, {
"label": "CFO",
"category": [{
"label": "Payables"
}, {
"label": "Receivables"
}]
}, {
"label": "CIO",
"category": [{
"label": "PR"
}, {
"label": "HR"
}]
}]
}]
You need to keep a list of categories and search for past occurences of org_lev1. I added a seperate method for that.
see complete solution:
public static void main(String[] args)
{
Connection connection = null;
PreparedStatement pst = null;
ResultSet rs = null;
PreparedStatement pst2 = null;
ResultSet rs2 = null;
LinkedHashMap<String, Object> parentCategory = new LinkedHashMap<String, Object>();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl","REF","REF");
String qstr = "select distinct PARENT_ORG_NAME from demo_org_data";
String qstr1 = "select distinct org_lev1,org_lev2 from demo_org_data";
pst = connection.prepareStatement(qstr);
rs = pst.executeQuery();
pst2 = connection.prepareStatement(qstr1);
rs2 = pst2.executeQuery();
while (rs.next()) {
List<Map<String, Object>> parentList = new ArrayList<>();
parentCategory.put("label", rs.getString(1));
parentCategory.put("category", parentList);
while (rs2.next()) {
String org_lev1 = rs2.getString(1);
String org_lev2 = rs2.getString(2);
Map<String, Object> subCategory = searchCategoryByLabel(parentList, org_lev1);
if (subCategory == null) {
subCategory = new LinkedHashMap<String, Object>();
subCategory.put("label", org_lev1);
subCategory.put("category", new ArrayList<Map<String, String>>());
parentList.add(subCategory);
}
List<Map<String, String>> subList = (List<Map<String, String>>)subCategory.get("category");
subList.add(Collections.singletonMap("label", org_lev2));
}
}
} catch (SQLException sql) {
System.out.println("SQLException occurred while fetching the data");
}
catch (Exception e) {
System.out.println("Exception occurred while fetching the data");
}
Map<String, List<Map<String, Object>>> outMap =
Collections.singletonMap("category", Collections.singletonList(parentCategory));
System.out.println(new Gson().toJson(outMap).toString());
}
public static Map<String, Object> searchCategoryByLabel(List<Map<String, Object>> list, String label)
{
for (Map<String, Object> map : list) {
if (map.containsKey("label") && map.get("label").toString().equals(label)) {
return map;
}
}
return null;
}
I got output:
{"category":[{"label":"CEO","category":[{"label":"CTO","category":[{"label":"Q \u0026 A Manager"},{"label":"Architect"},{"label":"Proj. Manager"}]},{"label":"CFO","category":[{"label":"Payables"},{"label":"Receivables"}]},{"label":"CIO","category":[{"label":"PR"},{"label":"HR"}]}]}]}
(hope you will appriciate the time I took to develop this)
You define a new category map for each entry in rs, so you will end up with several category maps. You want to put them inside one map that contains the category map and also rs.getString(1) so you need to define another (different) Map<String, Object> (call it allCategories) before the main loop, and then put in it rs.getString(1) and also category once it is populated.
Related
Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]
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;
}
I'm generating a JSON file in JAVA. The file contains a list of JSONs. I want to import this file to Azure Cosmos DB as soon as it is created.
Is there some way to achieve it from Java code?
Thanks in advance!
According to my research, if we want to implement bulk operations with java, we just can use bulk executor Java library. For more details, please refer to the document and article. Regarding how to use bulk executor Java library, please refer to the document.
For example
My .json file
[{
"id": "1",
"name": "test1",
"age": "20"
}, {
"id": "2",
"name": "test2",
"age": "21"
}, {
"id": "3",
"name": "test3",
"age": "22"
}, {
"id": "4",
"name": "test4",
"age": "23"
},
{
"id": "5",
"name": "test5",
"age": "24"
}, {
"id": "6",
"name": "test6",
"age": "25"
}, {
"id": "7",
"name": "test7",
"age": "26"
}, {
"id": "8",
"name": "test8",
"age": "27"
}
]
My pom.xml
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>documentdb-bulkexecutor</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Code
String endpoint="<your cosmos db endpoint>";
String key="<your key>";
ConnectionPolicy connectionPolicy = new ConnectionPolicy();
connectionPolicy.setMaxPoolSize(1000);
DocumentClient client = new DocumentClient(
endpoint,
key,
connectionPolicy,
ConsistencyLevel.Session);
String databaseId="testbulk";
String collectionId="items";
String databaseLink = String.format("/dbs/%s", databaseId);
String collectionLink = String.format("/dbs/%s/colls/%s", "testbulk", collectionId);
ResourceResponse<Database> databaseResponse = null;
Database readDatabase = null;
try {
databaseResponse = client.readDatabase(databaseLink, null);
readDatabase = databaseResponse.getResource();
System.out.println("Database already exists...");
} catch (DocumentClientException dce) {
if (dce.getStatusCode() == 404) {
System.out.println("Attempting to create database since non-existent...");
Database databaseDefinition = new Database();
databaseDefinition.setId(databaseId);
client.createDatabase(databaseDefinition, null);
databaseResponse = client.readDatabase(databaseLink, null);
readDatabase = databaseResponse.getResource();
} else {
throw dce;
}
}
ResourceResponse<DocumentCollection> collectionResponse = null;
DocumentCollection readCollection = null;
try {
collectionResponse = client.readCollection(collectionLink, null);
readCollection = collectionResponse.getResource();
System.out.println("Collection already exists...");
} catch (DocumentClientException dce) {
if (dce.getStatusCode() == 404) {
System.out.println("Attempting to create collection since non-existent...");
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.setId(collectionId);
PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();
Collection<String> paths = new ArrayList<String>();
paths.add("/id");
partitionKeyDefinition.setPaths(paths);
collectionDefinition.setPartitionKey(partitionKeyDefinition);
RequestOptions options = new RequestOptions();
options.setOfferThroughput(1000000);
// create a collection
client.createCollection(databaseLink, collectionDefinition, options);
collectionResponse = client.readCollection(collectionLink, null);
readCollection = collectionResponse.getResource();
} else {
throw dce;
}
}
System.out.println(readCollection.getId());
System.out.println(readDatabase.getId());
ArrayList<String> list = new ArrayList<String>();
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader("e:\\test.json")) {
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);
// cast jsonarry to string list
if (jsonArray != null) {
int len = jsonArray.size();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
System.out.println(list.get(0));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
// Set client's retry options high for initialization
client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(30);
client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(9);
// Builder pattern
DocumentBulkExecutor.Builder bulkExecutorBuilder = DocumentBulkExecutor.builder().from(
client,
databaseId,
collectionId,
readCollection.getPartitionKey(),
20000) ;// throughput you want to allocate for bulk import out of the container's total throughput
// Instantiate DocumentBulkExecutor
try {
DocumentBulkExecutor bulkExecutor = bulkExecutorBuilder.build();
// Set retries to 0 to pass complete control to bulk executor
client.getConnectionPolicy().getRetryOptions().setMaxRetryWaitTimeInSeconds(0);
client.getConnectionPolicy().getRetryOptions().setMaxRetryAttemptsOnThrottledRequests(0);
BulkImportResponse bulkImportResponse = bulkExecutor.importAll(list, false, false, null);
System.out.println(bulkImportResponse.getNumberOfDocumentsImported());
} catch (Exception e) {
e.printStackTrace();
}
Recently, I tried to code a list of linkman. I want to obtaining local data file(City.json) and parsing into listView. However ,the data from JsonObject always null. Help me please. I'm a Newbie. Thanks in advance.
the code under:
City.json
{
// "state": 1,
"datas": [
{
"id": "820",
"name": "安阳",
"sortKey": "A"
},
{
"id": "68",
"name": "安庆",
"sortKey": "A"
},
{
"id": "1269",
"name": "鞍山",
"sortKey": "A"
},
{
"id": "22",
"name": "蚌埠",
"sortKey": "B"
},
{
"id": "1372",
"name": "包头",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
}
]
}
AppFileReader.java
package me.sitinglin.administrator.wecharlinkmantest;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Created by Administrator on 2016/10/12.
*/
public class AppJsonFileReader {
public static String getJson(Context context, String fileName){
StringBuilder builder = new StringBuilder();
AssetManager manager = context.getAssets();
try {
InputStream stream = manager.open(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line = null;
while((line = bufferedReader.readLine())!=null){
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Log.i("abc", builder.toString());
return builder.toString();
}
public static List<City> setData(String str){
List<City> list = new ArrayList<>();
City city ;
try {
JSONObject result = new JSONObject(str);
JSONArray array = result.getJSONArray("datas");
// JSONArray array =new JSONArray(result);
int len = array.length();
Log.i("len", array.toString());
for (int i = 0; i <len ; i++) {
JSONObject object = array.optJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
}
}
this my context of logcat
Try this:
try {
JSONObject result = new JSONObject(str);
JSONArray jsonArray = result.getJSONArray("datas");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
You should go with following code :
JSONObject jobj = new JSONObject(str);
if(jobj.has("datas")){
JSONArray jsonArray = jobj.getJSONArray("datas");
List<City> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jdataObj = jsonArray.getJSONObject(i);
City city = new City();
city.setId(jdataObj.getString("id"));
city.setName(jdataObj.getString("name"));
city.setSortKey(jdataObj.getString("sortKey"));
list.add(city);
}
} else {
Log.e("Json","Json has no datas key.")
}
Hope this will help you.
I found 3 solution to solve this.i will list 3 things that i've solved below and one of the 3 solutions may helped you.
there are three point which one of three point maybe help U :
1. checking out the [local file name] of JSON;
2. checking out variale is "public " or "private"..;
3.checking out some Json method whether you are uesing correct?
Aha...
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;
}