I encountered a problem
{
"a": "X1abs",
"b": "d4vT"
}
This is to be done with plugin json-simple
So what I want is that if I have "X1abs"
, then I get the key which is "a"
Please Help me
I encountered a problem
{
"a": "X1abs",
"b": "d4vT"
}
This is to be done with plugin json-simple
So what I want is that if I have "X1abs"
, then I get the key which is "a"
Please Help me
Below code convert JSON to map
public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != JSONObject.NULL) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Below code identify the key based on the value:
for (Entry<Integer, String> entry : testMap.entrySet()) {
if (entry.getValue().equals("c")) {
System.out.println(entry.getKey());
}
}
If the value like “X1abs” is unique, then you could create a reverse map to store the value as the key, and the key as the value. Example like this:
Create a HashMap:
Map<String, String> reverseMap = new HashMap<>();
Then, for each object key : value, you do so:
reverseMap.put(value, key);
After you finalize the map, you could retrieve your key with the value, something like this:
String key = reverseMap.get(“X1abs”); // the key should be “a”
However, if the value is not unique, there is no unique solution on the key. You need a list of keys for each value, the map should be like this:
Map<String, List<String>> reverseMap = new HashMap<>();
Then, for each object (value, key) you do so:
reverseMap.computeIfAbsent(value, x -> new ArrayList<>()).add(key);
After the map is finalized, for each value you could retrieve a list of keys:
List<String> list = reverseMap.get(“X1abs”);
You can then iterate the list to get whatever value you want.