Obtain Inner JSON Array Values - java

I'm attempting to get the values for the "filterInputParameters" array within the serviceResponseValue map. Right now I have attempted to iterate through the map but could only obtain the first level of data such as the displayName and I need to go one-two levels deeper for the values in filterInputParamters array. Please let me know if you need more information.
Dart Code:
var jsonString = response;
var dropDown = querySelector("#asset");
Map jsonObject = JSON.decode(jsonString) as Map;
dropDownList = jsonObject["serviceResponseValue"] as List<Map>;
LinkedHashMap<String, Map> dataMap = new LinkedHashMap<String, Map>();
//the one causing issues and returning null
var ddValues2 = dropDownList
//extract the 'displayValue'
.map((e2) => e2['filterInputParameters']['value']);
//create a set to eliminate duplicates
//.toSet().toList()
//sort the result
//..sort();
ddValues2.forEach((e2) {
print(e2);
});

Map jsonObject = JSON.decode(jsonString) as Map;
print(jsonObject["serviceResponseValue"][0]["filterInputParameters"]);
In JSON [ ] indicate a List and { } a Map.
You access a list element by passing a numeric index (xxx[5] to get the 6th item)
and a String to access a Map item (xxx["serviceResponeValue"]).
Your JSON starts with
{ // the outer element is a map
"serviceResponseValue":[ // this map item can be accessed with a
// string index"serviceResponseValue"
// after the colon `:` starts the associated value, a list
// the first item can be accessed using [0]
{ // which contains a map
...
"filterInputParameters":[ // this item of the map is returned by ["filterInputParameters"]
{
"id":"8a4984e047d0e40d0147d0e410020008",

Related

How to retrieve value from Map<ArrayList<String>, Object>

I want to know how can I retrieve values from Map<ArrayList<String>, Object> Where the String and object are stored as Array [] for user define length.
Here is an Example:
int counter=0, n=0;
if (dataSnapshot.exists()){
for (DataSnapshot ds: dataSnapshot.getChildren()){
loca[counter]= new ArrayList<>();
itemListProduct[n]= new ItemListProduct();
itemListProduct[n]= ds.getValue(ItemListProduct.class);
loca[counter].add(testHeaderlist.get(counter));
System.out.println(ds.child("item_NAME").getValue(String.class));
objectMap.put(loca[counter],itemListProduct[n]);
counter++;
}
Here the testHeaderlist is an ArrayList<String> where there are some string stored.
I wanted to store data in the below Image manner:
So now my question is how can I retrieve the Key as well as the Object from "dataList". As from the code which I have shared at the TOP "n" number of list, and the object are stored in the dataList.
The thing is that I want to retrieve to use it in ExpandableListView. loca as header and itemListproduct as my value Object. Where the both are stored at objectMap.
Can anyone please solve it. Thank you!
It is permitted but rather atypical to have an ArrayList as a key to a map. To get the Object you need to do the following:
Object val = map.get(arrayList)
Here, arrayList must contain the exact same strings in the same order as the ArrayList key which refers to the desired object.
Example
Map<List<String>, Integer> map = new HashMap<>();
List<String> key = List.of("abc", "efg");
map.put(key, 20);
Integer v = map.get(List.of("efg","abc")); // different key so
// object not found
System.out.println(v); // prints null
v = map.get(List.of("abc", "efg"));
System.out.println(v); // prints 20
You can get all the Keys of a map by doing
Set<List<String>> set = map.keySet();
You also need to readup on HashMap and ArrayList to understand how they work. The following will keep replacing the object for the key of list[0]
dataList.put(list[0], object[0]);
dataList.put(list[0], object[1]);
dataList.put(list[0], object[2]);
dataList.put(list[0], object[3]);
When the above is done, list[0] will only refer to object[3]

How to get inner key in map

I want to get inner value of map. Here is the map.
{
"CUADO3": [
{
"C_E": 101,
"DESCRIPCION": "zz",
"N_M": 385.19,
"N_A": 37.45,
"MS_M": 62.2,
"MES": 16.42,
"ME": 79.91,
"MEF": 3.16
}
]
}
Here is my java code
Map<String,Object> map = dao.getVlaues();
IF I want to get with key I can Call Like
Object cua = map.get("CUADO3");
But I need inside of CUADO3 C_E I need How Can I get C_E from map.
If you are sure about the structure then you can cast the object to desired List and Map classes like below and fetch the internal map, then get any desired value from internal map.
Map<String,Object> map = dao.getVlaues();
List<Map> listOfMap = (List<Map>)map.get("CUADO3");
Map internalMap = listOfMap.get(0);
System.out.println(internalMap.get("C_E"));

How to loop through all values of a HashMap and print out any values containing a searched term

I have a map:
private HashMap<String, CompactDisc> database;
Every CompactDisc object has an artist, and I want to have a user enter a string and search through the hash-map and print out ALL values containing the string.
So if I searched "Jackson", I would get both The Jackson 5 and Michael Jackson (assuming they are in the CD).
Iterate through the values of the HashMap and check if the CompactDisc's artist name contains the specified string.
for (CompactDisc cd : database.values()) {
if(cd.getArtist().contains(searchString)){
System.out.println(cd.getArtist());
}
}
assuming CompactDisk has a getArtist() method that returns a String. And searchString is the string specified by user.
Commons Collections provides a nice way to filter a Collection of objects:
// Set up data
String searchString = "Jackson";
HashMap<String, CompactDisc> database = new HashMap<String, CompactDisc>();
database.put("key1", new CompactDisc("Jackson 5"));
database.put("key2", new CompactDisc("Michael Jackson));
database.put("key3", new CompactDisc("Random artist"));
List<CompactDisc> values = database.values();
CollectionUtils.filter(values , new Predicate<CompactDisc>(){
public boolean evaluate( CompactDisc obj ) {
return obj.getArtist().contains(searchString);
}
});
Given searchString = "Jackson", after invoking .filter the values list will contain only CompactDiscs with artists containing "Jackson".

Iterate through hash maps and object

I am gradually learning how to use Hashmaps , I have a map where i would be adding
HashMap( student id, other student records as object() ) .
I am trying to retrieve the values with their keys.
Please see below.
HashMap<String, Object> studentinfo = new HashMap<String, Object>();
List<Object> lstObject = new ArrayList<Object>();
studentinfo.put("student height", 5.01); //Put data in studentinfo hashmap
lstObject.add(studentinfo);
// New items hashmap
HashMap<String, Object> items = new HashMap<String, Object>();
//Put object in items hashmap
items.put("student id 001",lstObject); //Store data for 1st id student with 001
items.put("student id 002",lstObject); //Store data for 2nd id student with 002
for (Map.Entry<String, Object> entry : items.entrySet()) {
if(entry.getKey().equals("student id 001")){
//Get student id for only student id 001
System.out.println(entry.getValue());
// When i print this out , this is what i get
// [{student height=5.01}]
}
}
How can i loop thru to get the value only
Like this, for example:
5.01 // Student id 001
To get the value 5.01 which is stored in a map for the key "student height" within a list that is stored in another map under the key "student id 001", you'll need to code the access to that information. The outer map itself only knows of values and if you define the value type to be Object you'd have to cast yourself.
A better design might be to replace that list with a Student object which has a property height and access that.
But just for information, if you'd define your map like Map<String, List<Map<String, Object>> you'd be able to directly access the lists and their elements as values, e.g. (not handling null for simplicity):
Double height = (Double)items.get("student id 001").get(0).get("student height");
Just to reiterate: this is awkward design and should be changed, you'll probably realize that whith increasing experience and knowledge.
Better:
class Student {
double height;
Student(double h) {
height = h;
}
}
Map<String, Student> students = ...;
students.put("student 001", new Student(5.01) );
double height = students.get("student 001").height;
Note that I left out a lot of code for simplicity reasons such as modifiers, getters/setters, null checks etc.
Another note (added here instead of a comment for formatting reasons):
items.put("student id 001",lstObject); //Store data for 1st id student with 001
items.put("student id 002",lstObject); //Store data for 2nd id student with 002
This will put the same list as the value for both keys, i.e. if you change the list elements you'll change it for both student ids.

When JsonObject's keys are iterated they aren't in the same order as in the response from the server

I have a very large response from server of JSON string. I converted it to JSON object and then get the keys and iterate it.
The problem is that when I iterate it isnt in the same order as in response from server.
Next then I apply another method by adding all the keys in List<String> and the sort it and then get the iterator of that but still it isn't as I required (as in response).
Code example is here:
JSONObject jsonObject = new JSONObject(responseString);
Iterator<String> myIter = jsonObject.keys();
List<String> sortKey = new ArrayList<String>();
while(myIter.hasNext()){
sortKey.add(myIter.next());
}
Collections.sort(sortKey);
The order of the keys of a JSON object is not supposed to be meaningful. If you want a specific order, you should use an array, not an object.
Your Java code sorts the keys alphabetically. There is no way to get the initial ordering of the keys in the object.
Reference 1:
The order of the keys is undefined
Reference 2:
An object is an unordered set of name/value pairs
You can use Sorted map to put keys and values into. Something like this
public static List listFromJsonSorted(JSONObject json) {
if (json == null) return null;
SortedMap map = new TreeMap();
Iterator i = json.keys();
while (i.hasNext()) {
try {
String key = i.next().toString();
JSONObject j = json.getJSONObject(key);
map.put(key, j);
} catch (JSONException e) {
e.printStackTrace();
}
}
return new LinkedList(map.values());
}
I came across this similar problem while working on section in my android app which displays a list of 1024+ websites alphabetically. Since the json traversal was not in sorted order , I just inserted the json values during traversal into a table ( I m using list adapters in my app) and obtained sorted list of websites with cursor.
So if you are saving what you are fetching from server, you can just query your database to sort the values in the order your want.

Categories