Read hashmap with inner array of objects in java - java

This is a result I get from a hashmap in java. How do we read this and extract value1 and value2 and put them inside another hash map? And only one array of object inside.
{
"result": [
{
"desc": {
"value1": "",
"value2 ""
}
}
]
}
This is the method tried,
HashMap result = (HashMap) response.get("result");
HashMap desc = (HashMap) result.get("desc");
map.put("value1", desc.get("value1"));
map.put("value2", desc.get("value2"));

You're missing the List level
List<Object> result = (List<Object>) response.get("result");
HashMap<String,Object> item = (HashMap<String,Object>) result.get(0);
HashMap<String,String> desc = (<String,String>) item.get("desc");
map.put("value1", desc.get("value1"));
map.put("value2", desc.get("value2"));

Related

How to iterate for loop and get values from List<List<Map<String, String>>>

I want to iterate the Arraylist of Arraylist, get the values and insert them into table. My code is working for single Arraylist. What I have achieved for single list is:
private String setreportColLinksBean(List<Map<String, String>> allValuesMap) {
for (Map<String, String> result: allValuesMap) {
Map<String, String> map = new HashMap<String, String>();
if (result.get("it_datatype") != null) {
map.put("it_datatype", (String) result.get("it_datatype"));
it_datatype = result.get("it_datatype");
}
if (result.get("item_value") != null) {
map.put("item_value", (String) result.get("item_value"));
item_value = result.get("item_value");
}
ReportLinks reportlinks = new ReportLinks();
reportlinks.setItem_datatype(it_datatype);
reportlinks.setItem_value(item_value);
saveReportLinks(reportlinks);
}
}
But I want to iterate data which is like this:
[
[
{it_datatype=Character, at_desc=Scholarship Form, it_code=ITM0001, at_bpcode=PR00000122},
{it_datatype=Character, at_desc=Scholarship Form, it_code=ITM0002, at_bpcode=PR00000122}
],
[
{it_datatype=Character, at_desc=initiate 2, it_code=ITM0001, at_bpcode=PR00000625},
{it_datatype=Character, at_desc=initiate 2, it_code=ITM0002, at_bpcode=PR00000625}
]
]
How do I iterate this list and get the values for inserting them into the table. I am very new to Java. Please help. TIA.
Add a for loop around it. The dots are the there for abbreviation.
public void save(List<List<Map<String, String>>> nestedLists) {
for(var nestedList : nestedLists) {
setreportColLinksBean(nestedList);
}
}

How to construct this JSON array of JSONObjects

I have a Problem which I have to solve in Java.I have a data in YAML where the data is in this structure
600450:
STATE:STATE1
CITY:CITY1
ID:1
CONTACT:1234
600453:
STATE:STATE1
CITY:CITY1
ID:2
CONTACT:3456
600451:
STATE:STATE2
CITY:CITY2
ID:3
CONTACT:2234
.....
I converted this into JSONObject but I am strugling to change this into this JSONObject object where the structure should be of this form
{
STATE1:
{[
CITY1:{
[{ID:1,CODE:600450,CONTACT:1234},
{ID:2,CODE:600453,CONTACT:3456}
]
},
CITY2:{
[
{ID:3,CODE:600451,CONTACT:1234}
]
}
]}
}
I have almost lost a hour by doing different Things with JSONObject and JSONArray and then switched to HashMap and ArrayList of HashMap but I am not able to get it !
This was my try I am sure this is absurd I know that How to achieve this in Java .
Assuming that your converted initial JSON looks like this:
{
"600450": {
"STATE": "STATE1",
"CITY": "CITY1",
"ID": 1,
"CONTACT": 1234
},
"600451": {
"STATE": "STATE2",
"CITY": "CITY2",
"ID": 3,
"CONTACT": 2234
},
"600453": {
"STATE": "STATE1",
"CITY": "CITY1",
"ID": 2,
"CONTACT": 3456
}
}
Here is a static method that does the full conversion to your desired format:
static JSONObject convert(JSONObject initial) {
// STATE -> CITY -> Address[]
Map<String, Map<String, List<Map<String, Object>>>> stateToCityToAddresses = new HashMap<>();
// Get list of codes
String[] codes = JSONObject.getNames(initial);
// Loop over codes - "600450", "600451", "600453", ...
for (String code : codes) {
// Get the JSONObject containing state data
JSONObject state = initial.getJSONObject(code);
// Extract information from state JSONObject
String stateName = state.getString("STATE");
String cityName = state.getString("CITY");
long id = state.getLong("ID");
long contact = state.getLong("CONTACT");
// Some Java 8 awesomeness!
List<Map<String, Object>> addresses = stateToCityToAddresses
.computeIfAbsent(stateName, sn -> new HashMap<>()) // This makes sure that there is a Map available to hold cities for a given state
.computeIfAbsent(cityName, cn -> new ArrayList<>()); // This makes sure that there is a List available to hold addresses for a given city
// Save data in a map representing a json object like: {"CONTACT":1234,"CODE":600450,"ID":1}
Map<String, Object> address = new HashMap<>();
address.put("ID", id);
address.put("CONTACT", contact);
address.put("CODE", Long.parseLong(code));
// Add the address under city
addresses.add(address);
}
// Just use the JSONObject.JSONObject(Map<?, ?>) constructor to get the final result
JSONObject result = new JSONObject(stateToCityToAddresses);
// You can sysout the result to see the data
// System.out.println(result);
return result;
}
Allow me to play Devil's Advocate.
I think you may risk deviating away from the relationships that have been described in the .yaml. You should try to avoid embedding any application-specific logic inside of your data models, since your assumptions may land you in trickier places in the future.
Generally speaking, you should respect the initial form of the data and interpret the relationships or associated logic with the flexibility of runtime processing. Otherwise, you end up serializing data structures which do not correlate directly with the source, and your assumptions may land you in a hot spot.
The "real" JSON equivalent, I suspect; would look something like this:
{
"600450": {
"STATE": "STATE1",
"CITY": "CITY1",
"ID": 1,
"CONTACT": 1234
},
"600453": { ...etc }
}
It would still be possible to pair these relationships. If you want to relate all Objects by city, you could first separate them into bins. You could do this by using a Map which relates a String city to a List of JSONObjects:
// This will be a Map of List of JSONObjects separated by the City they belong to.
final Map<String, List<JSONObject>> mCityBins = new ArrayList();
// Iterate the List of JSONObjects.
for(final JSONObject lJSONObject : lSomeListOfJSONObjects) {
// Fetch the appropriate bin for this kind of JSONObject's city.
List<JSONObject> lBin = mCityBins.get(lJSONObject.get("city"));
// Does the right bin not exist yet?
if (lBin == null) {
// Create it!
lBin = new ArrayList();
// Make sure it is in the Map for next time!
mCityBins.add(lJSONObject.get("city"), lBin);
}
// Add the JSONObject to the selected bin.
lBin.add(lJSONObject);
}
Whilst you process the JSONObjects, whenever you come across a city whose key does not exist in the Map, you can allocate a new List<JSONObject>, add the current item to that List and add it into the Map. For the next JSONObject you process, if it belongs to the same city, you'd find the existing List to add it to.
Once they're separated into bins, generating the corresponding JSON will be easy!
As I see your git repo you just try to convert first Json structure to new Structure you want. I must to tell you probably you could create this structure directly from YAML file.
As I don't see your first Json structure so I guess that must be something like this :
{600450:{STATE:STATE1 , CITY:CITY2 , ...} , ...}
If this is true so this way can help you :
public static JSONObject convert(JSONObject first) throws JSONException {
HashMap<String , HashMap<String , JSONArray>> hashMap = new HashMap<>();
Iterator<String> keys = first.keys();
while (keys.hasNext())
{
String key = keys.next();
JSONObject inner = first.getJSONObject(key);
String state = inner.getString("STATE");
HashMap<String , JSONArray> stateMap =
hashMap.computeIfAbsent(state , s -> new HashMap<>());
String city = inner.getString("CITY");
JSONArray array = stateMap.computeIfAbsent(city , s->new JSONArray());
JSONObject o = new JSONObject();
o.put("ID" , inner.getInt("ID"));
//in this section you could create int key by calling Integer.parse(String s);
o.put("CODE" , Integer.valueOf(key));
o.put("CONTACT" , inner.getInt("CONTACT"));
array.put(o);
}
JSONObject newStructureObject = new JSONObject();
for(String stateKey:hashMap.keySet())
{
JSONArray array = new JSONArray();
JSONObject cityObject = new JSONObject();
HashMap<String , JSONArray> cityMap = hashMap.get(stateKey);
for(String cityKey : cityMap.keySet())
{
cityObject.put(cityKey , cityMap.get(cityKey));
}
array.put(cityObject);
newStructureObject.put(stateKey , array);
}
return newStructureObject;
}

Generating JSON out put using two separate list with Java

I am using Java and have two list, one have field names and other have values. I am generating JSON using list values and it is working fine as shown below.
String json = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().
create().toJson(fieldValues );
fileOut.println(json);
Repetitive field values are coming like this:
[
"2017-10-02T21:06:08.134061801Z",
"sensor_2000:,
"10",
1.0
],
[
"2017-10-02T21:06:08.134061801Z",
"sensor_1000:,
"20",
2.0
],
Now i have another small constant field list having field names in it, which have contents as shown below:
[
"time",
"sensor",
"sequence_number",
"component_id"
]
How can i merge columns names list with the first list having values, and get the out put like this:
[
"time":"2017-10-02T21:06:08.134061801Z",
"sensor":"sensor_2000:,
"sequence_number":"10",
"component_id":1.0
],
[
"time":"2017-10-02T21:06:08.134061801Z",
"sensor":"sensor_1000:,
"sequence_number":"20",
"component_id":2.0
],
If I understood correctly, you have 2 lists: one with the values and the other one with the names.
Values:
[["2017-10-02T21:06:08.134061801Z","sensor_2000:",10,1.0],["2017-10-02T21:06:08.134061801Z","sensor_1000:",20,2.0]]
Names:
[time, sensor, sequence_number, component_id]
You can use the JsonObject in order to achieve your goal. In particular the addProperty method
Here is it the example:
Gson gson= new Gson();
List<Object> finalValue= new LinkedList<>();
List<Object> value= new LinkedList<>();
List<Object> value2= new LinkedList<>();
List<String> names= new LinkedList<>();
value.add("2017-10-02T21:06:08.134061801Z");
value.add("sensor_2000:");
value.add(10);
value.add(1.0);
value2.add("2017-10-02T21:06:08.134061801Z");
value2.add("sensor_1000:");
value2.add(20);
value2.add(2.0);
finalValue.add(value);
finalValue.add(value2);
names.add("time");
names.add("sensor");
names.add("sequence_number");
names.add("component_id");
System.out.println("values: " + gson.toJson(finalValue));
System.out.println("names: " + names);
LinkedList<JsonObject> finalList= new LinkedList<>();
for(Object obj: finalValue)
{
JsonObject jsonObj= new JsonObject();
List<Object> valueObj = (List<Object>) obj;
int i=0;
for(Object innerObj: valueObj)
{
if(names.get(i).equalsIgnoreCase("component_id"))
{
jsonObj.addProperty(names.get(i), Double.parseDouble(String.valueOf(innerObj))) ;
}
else if(names.get(i).equalsIgnoreCase("sequence_number"))
{
jsonObj.addProperty(names.get(i), Integer.parseInt(String.valueOf(innerObj))) ;
}
else {
jsonObj.addProperty(names.get(i), String.valueOf(innerObj)) ;
}
i++;
}
finalList.add(jsonObj);
}
System.out.println(gson.toJson(finalList));
}

Get values of jsonarray using other jsonarray values as a key

I'm getting following json from server:
{
"Data": [
{
"Record": [
" d11",
"d12"
]
},
{
"Record": [
" d21",
"d22"
]
}
],
"Keys": [
"Key1",
" key2"
]
}
I want to retrieve record values which are ordered with respect to keys values(key1, key2?
Note: Using org.json api only.
Your question is still a little unclear to me, but I'm assuming you want to turn that JSON into a list of records, where each record is (for example) a map containing the keys from the list of keys and the values from the data list.
In order to achieve this, we first parse the JSON into a JSONObject:
String json = " ... ";
JSONTokener tokener = new JSONTokener(json);
JSONObject jsonObject = new JSONObject(tokener);
Then we extract the list of keys and the data list:
JSONArray data = jsonObject.getJSONArray("Data");
JSONArray keys = jsonObject.getJSONArray("Keys");
and define a list to contain our output:
List<Map<String, String>> records = new ArrayList<>();
Finally, we iterate over the data list, extract the list of record values for each item in that list, and then iterate over the keys in order to create a map from key to record value:
for (int i = 0; i < data.length(); i++) {
JSONObject dataItem = data.getJSONObject(i);
JSONArray recordValues = dataItem.getJSONArray("Record");
Map<String, String> record = new HashMap<>();
for (int j = 0; j < keys.length(); j++) {
String key = keys.getString(j);
String value = recordValues.getString(j);
record.put(key, value);
}
records.add(record);
}
When we then print the value of records, we get something that looks like:
[{Key1= d11, key2=d12}, {Key1= d21, key2=d22}]

Fetch the json keys using java

I have a json object how can I get all the keys and later without hard coding the keys how can I get the key values.
{
"A":"M1",
"Data":[
{
"B":[
{
"B1":"111",
"B2":"Warning "
},
{
"B1":"222",
"B2":"Warning "
}
],
"C":[
{
"c1":"IL2",
"c2":"[0.750183,0.00933380975964486]"
},
{
"c1":"IL1b",
"c2":"[0.750183,-1.5216938335421]"
}
]
}
]
}
Try this out...
This might work for you....
You have to use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
Roughly the code will look like:
// searchResult refers to the current element in the array "search_result"
JSONObject questionMark = searchResult.getJSONObject("question_mark");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}

Categories