Check if JSONObject matches JSON boolean expression - java

To explain correctly the problem I must start with an example let's say I have a list of users like this
[
{ "name": "John", "surname": "Doe", "age": 22 },
{ "name": "Syrus", "surname": "Black", "age": 20 }
]
And I have also a JSONObject representing a condition that must be matched like this:
{
"OR":[
{ "name": { "eq": "John"} },
{ "AND":[
{ "name": { "eq": "Syrus"} },
{ "age": { "gt": 18 } }
] }
]
}
Which should be translated in:
name = "John" OR (name = "Syrus" AND age > 18)
Now I have to make the code that given the JSONObject condition and the list of the users checks for each users if the condition is matched.
At the moment this is what I have done:
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import com.query.Queryable;
import org.json.JSONArray;
import org.json.JSONObject;
public class QueryableTreeMap<K,V extends JSONObject> extends TreeMap<K,V> implements Queryable<JSONObject,JSONObject> {
private static final long serialVersionUID = 2586026774025401270L;
private static boolean test(Set<Map.Entry<String, Object>> condition, JSONObject value){
boolean isValid = true;
Iterator<Map.Entry<String, Object>> iter = condition.iterator();
while(iter.hasNext()){
Map.Entry<String, Object> subcond = iter.next();
if(subcond.getKey().equals("OR")){
//isValid = isValid || test((Set<Map.Entry<String, Object>>) subcond.getValue(), value);
} else if(subcond.getKey().equals("AND")){
//isValid = isValid && test((Set<Map.Entry<String, Object>>) subcond.getValue(), value);
} else if(subcond.getKey().equals("NOT")){
} else {
}
}
return isValid;
}
#Override
public JSONObject query(JSONObject query) {
// the set containing the conditions
Set<Map.Entry<String, Object>> entries = query.toMap().entrySet();
// the JSONArray with containing the records that match the condition
JSONArray array = new JSONArray();
// for each JSONObject inside this structure
this.forEach(new BiConsumer<K,JSONObject>(){
#Override
public void accept(K key, JSONObject value) {
// testing if the current record matches the condition
if(test(entries, value)) array.put(value);
}
});
// returns a JSONObject containing a JSONArray that contains the records that match the condition
return new JSONObject(array);
}
}
I am currently stuck in the test method which should in-fact test if the given object matches the given condition.
I don't mind changing the format of the JSON condition as long as it is a JSONObject.
At the moment i have come up with a partial solution that builds an object called Condition that represents the boolean expression inside the JSONObject (not very efficient but still a possible solution) this is obviously not working at the moment, i need help on what i should do now
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Condition {
private Condition left, right;
private String boolExpr, key, value;
private boolean not;
private int operationType; // greater then, less then, equal to, greater or equal of, less or equal of
public Condition(Map<String, Object> map) {
Set<Map.Entry<String, Object>> set = map.entrySet();
Iterator<Map.Entry<String, Object>> iterator = set.iterator();
while(iterator.hasNext()){
Object entry = iterator.next();
System.out.println(entry);
System.out.println(entry.getClass());
if(entry instanceof Map.Entry) {
String key = (String) ((Map.Entry) entry).getKey();
switch(key){
case "AND":
case "OR":
this.boolExpr = key;
break;
case "eq":
case "gt":
case "lt":
case "gte":
case "lte":
this.operationType = getOperationTypeFromString(key);
break;
case "NOT":
this.not = true;
break;
default:
this.key = key;
break;
}
}
}
}
public int getOperationTypeFromString(String operation) {
switch(operation){
case "eq":
return 0;
case "gt":
return 1;
case "lt":
return 2;
case "gte":
return 3;
case "lte":
return 4;
default:
return 0;
}
}
}
I would prefer not to use the Condition class and just use the JSONObject instead.
I am using the org.json JSON-Java parser.

Edit: code updated to use org.json.
Below is a working implementation that handles your example.
The function that actually does the work is match, which recursively traverses the filter and applies each node to the supplied object. The function returns true if the given object satisfies the given filter.
Conceptually the match function is mapping each construct in your filter language (AND, OR, EQ, LT etc) into its Java equivalent. E.g. AND maps to Stream.allMatch, NOT maps to the Java ! operator, EQ maps to Object.equals, etc. I.e. match is defining the semantics for your filter language.
I hope the code is self-explanatory - let me know if anything is unclear.
import org.json.*;
import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.*;
import static java.util.stream.Collectors.toList;
public class Test {
public static void main(String[] args) throws IOException {
final List<JSONObject> jsObjs =
stream(readJsonArray("users.json"))
.map(JSONObject.class::cast)
.collect(toList());
final JSONObject jsFilter = readJsonObject("filter.json");
final List<JSONObject> matches = applyFilter(jsObjs, jsFilter);
System.out.println(matches);
}
private static List<JSONObject> applyFilter(List<JSONObject> jsObjs, JSONObject jsFilter) {
return jsObjs.stream()
.filter(jsObj -> match(jsObj, jsFilter))
.collect(toList());
}
private static boolean match(JSONObject jsObj, JSONObject jsFilter) {
final String name = getSingleKey(jsFilter);
final Object value = jsFilter.get(name);
switch (name) {
case "AND":
return stream((JSONArray)value)
.map(JSONObject.class::cast)
.allMatch(jse -> match(jsObj, jse));
case "OR":
return stream((JSONArray)value)
.map(JSONObject.class::cast)
.anyMatch(jse -> match(jsObj, jse));
case "NOT":
return !match(jsObj, (JSONObject)((JSONArray)value).get(0));
default:
final JSONObject jsOp = (JSONObject)value;
final String operator = getSingleKey(jsOp);
final Object operand = jsOp.get(operator);
switch (operator) {
case "eq": return jsObj.get(name).equals(operand);
case "lt": return (Integer)jsObj.get(name) < (Integer)operand;
case "gt": return (Integer)jsObj.get(name) > (Integer)operand;
default: throw new IllegalArgumentException("Unexpected operator: " + operator);
}
}
}
private static JSONObject readJsonObject(String fileName) throws IOException {
try (Reader reader = Files.newBufferedReader(Paths.get(fileName))) {
return new JSONObject(new JSONTokener(reader));
}
}
private static JSONArray readJsonArray(String fileName) throws IOException {
try (Reader reader = Files.newBufferedReader(Paths.get(fileName))) {
return new JSONArray(new JSONTokener(reader));
}
}
private static Stream<Object> stream(JSONArray jsa) {
return StreamSupport.stream(jsa.spliterator(), false);
}
private static String getSingleKey(JSONObject jso) {
if (jso.length() != 1) {
throw new IllegalArgumentException("Expected single entry");
} else {
return jso.keySet().iterator().next();
}
}
}

Related

How to parse JSON without POJO

This is my json:
{
"taggedEntries": {
"user/f8cf24ef-4bd0-846f-a11a781ce81a/tag/TEST": [
"20HQtzLrqRe8xz8tybYf2aS087xS92Zi_1719877dbea:8e4:6eb16f2b"
],
"user/f8cf24ef-4bd0-846f-a11a781ce81a/tag/global.unsaved": [
"360ebRQH+hi4mCv/YibdkukUtv175h4JfU23PTw2O8M=_171888f776b:69cb:f8e58482",
"20HQtzL4prqRe8xz8tybYf2aS087xS92Zi+zuo=_171987c5e49:8ed:6eb16f2b",
"20HQtzL4rqRe8xz8tybYf2aS087xS92Zi+zuo=_171987d5d3d:8ee:6eb16f2b",
"20HQtzL4q9uNe8xz8tybYf2aS087xS92Zi+zuo=_1719854c09a:8bd:6eb16f2b"
],
"user/f8cf24ef-4bd0-846f-a11a781ce81a/tag/286f1f46-911c-4bc2-4b028b0d7ed0": [
"v1I7ZIsSoGZxr80NFebazQf2J2QviXCcdot3TOU=_1717e68bf58:fcd1:75b51987",
"360ebRQH+hibdkukUtv175h4JfU23PTw2O8M=_171888f776b:69cb:f8e58482",
"20HQtzL4q9uqRe8xz8tybYf2aS087xS92Zi+zuo=_171983b3399:8b7:6eb16f2b"
]
}
}
How can I parse it?
I would like to get the following structure
TaggedEntries<String, Array<String>>
where:
1 argument is tag name, 2 argument is ids tag
Tag name is a dynamic string. I can't get as static element of json.
Any idea?
Thanks for help :)
Parse to Map<String, Map<String, List<String>>> then call get("taggedEntries") to get the Map<String, List<String>> value you're looking for.
In your TaggedEntries class you should have HashMap>. I think your argument without POJO is hard or messy I think. You'll play with alot of JsonObject / JsonArray.
My solution:
val obj = JsonParser().parse(jsonStr).asJsonObject.getAsJsonObject("taggedEntries")
val entries = obj.entrySet() //will return members of your object
val data = mutableMapOf<String,ArrayList<String>>()
for ((key) in entries) {
val ids: JsonArray = obj.getAsJsonArray(key)
val listIdTags = arrayListOf<String>()
ids.forEach{
listIdTags.add(it.toString())
}
data.put(key,listIdTags)
}
// Print Data
data.forEach(){ key, value ->
println("Key: $key")
println("Value:")
value.forEach{
println( it)
}
}
Maybe there is a better solution but I haven't found it. If you have a solution I'd like to hear it.
When you need some special things, you may need some special handiwork to be done and this isn't a rocket science, really :) For example, using a tiny JSON parser
https://github.com/anatolygudkov/green-jelly:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ParseMyJson {
private static final String myJson = "{" +
"\"taggedEntries\": {" +
"\"user/f8cf24ef-4bd0-846f-a11a781ce81a/tag/TEST\": [" +
"\"20HQtzLrqRe8xz8tybYf2aS087xS92Zi_1719877dbea:8e4:6eb16f2b\"]," +
"\"user/f8cf24ef-4bd0-846f-a11a781ce81a/tag/global.unsaved\": [" +
"\"360ebRQH+hi4mCv/YibdkukUtv175h4JfU23PTw2O8M=_171888f776b:69cb:f8e58482\"," +
"\"20HQtzL4prqRe8xz8tybYf2aS087xS92Zi+zuo=_171987c5e49:8ed:6eb16f2b\"," +
"\"20HQtzL4rqRe8xz8tybYf2aS087xS92Zi+zuo=_171987d5d3d:8ee:6eb16f2b\"," +
"\"20HQtzL4q9uNe8xz8tybYf2aS087xS92Zi+zuo=_1719854c09a:8bd:6eb16f2b\"" +
"]," +
"\"user/f8cf24ef-4bd0-846f-a11a781ce81a/tag/286f1f46-911c-4bc2-4b028b0d7ed0\": [" +
"\"v1I7ZIsSoGZxr80NFebazQf2J2QviXCcdot3TOU=_1717e68bf58:fcd1:75b51987\"," +
"\"360ebRQH+hibdkukUtv175h4JfU23PTw2O8M=_171888f776b:69cb:f8e58482\"," +
"\"20HQtzL4q9uqRe8xz8tybYf2aS087xS92Zi+zuo=_171983b3399:8b7:6eb16f2b\"" +
"]" +
"}" +
"}";
public static void main(String[] args) {
final TaggedEntries<String, String> result = new TaggedEntries<>();
final JsonParser parser = new JsonParser();
parser.setListener(
new JsonParserListenerAdaptor() {
private String lastPropertyName = null;
private boolean inArray = false;
public boolean onObjectMember(final CharSequence name) {
lastPropertyName = name.toString();
return true;
}
#Override
public boolean onArrayStarted() {
inArray = true;
result.onTag(lastPropertyName);
return true;
}
#Override
public boolean onArrayEnded() {
inArray = false;
return true;
}
#Override
public boolean onStringValue(final CharSequence data) {
if (inArray) {
result.onValue(data.toString());
}
return true;
}
}
);
parser.parse(myJson);
parser.eoj();
System.out.println(result);
}
public static class TaggedEntries<T, V> {
private final Map<T, List<V>> allEntries = new HashMap();
private List<V> currentTagValues;
public TaggedEntries() {
}
public void onTag(final T tag) {
currentTagValues = new ArrayList<>();
allEntries.put(tag, currentTagValues);
}
public void onValue(final V value) {
if (currentTagValues == null) {
throw new IllegalStateException("onTag must be called before");
}
currentTagValues.add(value);
}
public List<V> tagValues(final T tag) {
return allEntries.get(tag);
}
public Set<T> tags() {
return allEntries.keySet();
}
#Override
public String toString() {
final StringBuilder result = new StringBuilder("TaggedEntries{\n");
allEntries.forEach((t, vs) -> {
result.append('\t').append(t).append('\n');
vs.forEach(v -> result.append("\t\t").append(v).append('\n'));
});
result.append('}');
return result.toString();
}
}
}

Hash json and compare in Java

I am doing some migration & I would like to compare JSON Requests being sent on new vs old service. I have some sensitive data in my JSON, so I don't want to log it directly, I want to hash and then log it. Once hashed I want to compare the hashes.
PS: I have complex JSON Strings
{'method': 'do.stuff', 'params': ['asdf', 3, {'foo': 'bar'}]}
and
{'params': ['asdf', 3, {'foo': 'bar'}], 'method': 'do.stuff'}
Should return the same hash irrespective of the order
One way of doing this would be to sort the keys of each object so the JSON would be in the same order and then create a hash. You need to take care of nested objects and arrays also.
For example...
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.DigestUtils;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class JsonHash {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonStringA = "{\"a\": \"100\", \"b\": \"200\", \"c\": [{\"d\": 200, \"e\": 100}], \"p\": null}";
String jsonStringB = "{\"p\": null, \"b\": \"200\", \"a\": \"100\", \"c\": [{\"e\": 100, \"d\": 200}]}";
String jsonStringC = "{\"p\": 1, \"b\": \"200\", \"a\": \"100\", \"c\": [{\"e\": 100, \"d\": 200}]}";
String hashA = getHash(mapper, jsonStringA);
String hashB = getHash(mapper, jsonStringB);
String hashC = getHash(mapper, jsonStringC);
System.out.println(hashA);
System.out.println(hashB);
System.out.println(hashC);
}
private static String getHash(ObjectMapper mapper, String jsonStringA) throws IOException {
JsonNode jsonNode = mapper.readTree(jsonStringA);
Map map = mapper.convertValue(jsonNode, Map.class);
TreeMap sorted = sort(map);
String s = mapper.writeValueAsString(sorted);
byte[] md5Digest = DigestUtils.md5Digest(s.getBytes());
return DatatypeConverter.printHexBinary(md5Digest).toUpperCase();
}
private static TreeMap sort(Map map) {
TreeMap result = new TreeMap();
map.forEach((k, v) -> {
if(v != null) {
if (v instanceof Map) {
result.put(k, sort((Map) v));
} else if (v instanceof List) {
result.put(k, copyArray((List) v));
} else {
result.put(k, v);
}
} else {
result.put(k, null);
}
});
return result;
}
private static List copyArray(List v) {
List result = new ArrayList(v.size());
for (int i = 0; i < v.size(); i++) {
Object element = v.get(i);
if(element != null) {
if (element instanceof Map) {
result.add(sort((Map) element));
} else if (element instanceof List) {
result.add(copyArray((List) element));
} else {
result.add(element);
}
} else {
result.add(null);
}
}
return result;
}
}
Output:
FADE525B0423415184D913299E90D959
FADE525B0423415184D913299E90D959
B49993CB657F1C9A62A339E5482F93D1
The hash of your examples both come out as 3EBAD6BDF5064304B3DD499BDAF0E635

Json String to map convertor,

I am trying to write a generic code for nested JsonObject to map conversion.
I have a sample JSONObject as
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized \n Markup Language",
"GlossDef": {
"para": "A DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
I want to convert it into map having key value as
glossary.title = "example glossary",
glossary.GlossDiv.title = "S",
glossary.GlossDiv.GlossList.GlossEntry.ID ="SGML",
glossary.GlossDiv.GlossList.GlossEntry.SortAs ="SGML",
glossary.GlossDiv.GlossList.GlossEntry.GlossTerm="Standard Generalized
Markup Language",
glosary.GlossDiv.GlossList.GlossEntry.GlossDef.para ="A DocBook.",
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso_0 = "GML",
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso_1 = "XML",
glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSee = "markup"
This is method to read Map from json string using Jackson:
public final class JsonUtils {
public static <T> Map<String, T> readMap(String json) throws Exception {
if (json == null)
return null;
ObjectReader reader = new ObjectMapper().readerFor(Map.class);
MappingIterator<Map<String, T>> it = reader.readValues(json);
if (it.hasNextValue()) {
Map<String, T> res = it.next();
return res.isEmpty() ? Collections.emptyMap() : res;
}
return Collections.emptyMap();
}
}
This is how to read Map from json using given utilit method:
Map<String, String> map = flatMap(new LinkedHashMap<>(), "", JsonUtils.readMap(json));
And finally, this is how to transfrom Map into required Map (probably this could be done within Jackson engine, with provided custom deserializers or so, but I do not know exactly how, and thats why it is easier to me to implement it manually):
public static Map<String, String> flatMap(Map<String, String> res, String prefix, Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = prefix + entry.getKey();
Object value = entry.getValue();
if (value instanceof Map)
flatMap(res, key + '.', (Map<String, Object>)value);
else
res.put(key, String.valueOf(value));
}
return res;
}
Jackson JSON is a pretty cool library which does this for you. I wrote a quick example below but you should be able to apply this to your JSONObject.
Let's say you have A.class with property B.class who in turn has a nested property C.class
#JsonPropertyOrder({ "b" })
class A {
#JsonProperty("b")
public B b;
#JsonProperty("b")
public B getB() {
return b;
}
#JsonProperty("b")
public void setB(B b) {
this.b = b;
}
}
#JsonPropertyOrder({ "c" })
class B {
#JsonProperty("c")
public C c;
#JsonProperty("c")
public C getC() {
return c;
}
#JsonProperty("c")
public void setC(C c) {
this.c = c;
}
}
#JsonPropertyOrder({ "d" })
class C {
#JsonProperty("d")
public String d;
#JsonProperty("d")
public String getD() {
return d;
}
#JsonProperty("d")
public void setD(String d) {
this.d = d;
}
}
You can convert a nested JSONObject {"b":{"c":{"d":"test"}}} into A.class like this:
C c = new C();
c.setD("test");
B b = new B();
b.setC(c);
JSONObject obj = new JSONObject();
obj.put("b", b);
String jsonAsString = new Gson().toJson(obj);
A a = mapper.readValue(jsonAsString, A.class);
Similarly you should be able to convert your JSONObject into any type you want. Hope this helps
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonToMapConvertor {
private static HashMap<String, Object> mapReturn = new HashMap<String, Object>();
public static JsonParser parser = new JsonParser();
public static void main(String[] args) throws Exception{
String json ="add your Json";
HashMap<String, Object> map = createHashMapFromJsonString(json,"");
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(!entry.getValue().toString().contains("{"))
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
public static HashMap<String, Object> createHashMapFromJsonString(String json,String prefix) {
JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
if(prefix.length()!=0){
key = prefix + "."+key;
}
JsonElement value = entry.getValue();
if (null != value) {
if (!value.isJsonPrimitive()) {
if (value.isJsonObject()) {
mapReturn.put(key,value);
mapReturn.put(key, createHashMapFromJsonString(value.toString(),key));
} else if (value.isJsonArray() && value.toString().contains(":")) {
List<HashMap<String, Object>> list = new ArrayList<>();
JsonArray array = value.getAsJsonArray();
if (null != array) {
for (JsonElement element : array) {
list.add(createHashMapFromJsonString(value.toString(),key));
}
mapReturn.put(key, list);
}
} else if (value.isJsonArray() && !value.toString().contains(":")) {
mapReturn.put(key, value.getAsJsonArray());
}
} else {
mapReturn.put(key, value.getAsString());
}
}
}
return mapReturn;
}
}

Copy filtered JSON data from one file to another using gson library in java

I want to copy JSON fields from one file to another but only after the field satisfies a particular condition, as for example
{"dataset":
[
{"album_id":1,
"album_type":"Live Performance",
"artist_name":"John Doe",....
}
]
}
I want to copy only those records which have a user given artist_name or any other property, else skip the tuple for copying. I am using the following code to add the filtered records to a JSONObject "wr" which I then write to my output file. But its not giving me the desired results
public static void dumpJSONElement(JsonElement element) {
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
java.util.Set<java.util.Map.Entry<String,JsonElement>> entries = obj.entrySet();
java.util.Iterator<java.util.Map.Entry<String,JsonElement>> iter = entries.iterator();
while (iter.hasNext()) {
java.util.Map.Entry<String,JsonElement> entry = iter.next();
if(entry.getKey().equals(filterKey)){
if(! entry.getValue().toString().replace("\"", "").equals(filterValue)){
wr.put(entry.getKey(), entry.getValue());
}
}
else{
wr.put(entry.getKey(), entry.getValue());
}
dumpJSONElement(entry.getValue());
}
} else if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
java.util.Iterator<JsonElement> iter = array.iterator();
while (iter.hasNext()) {
JsonElement entry = iter.next();
dumpJSONElement(entry);
}
} else if (element.isJsonPrimitive()) {
JsonPrimitive value = element.getAsJsonPrimitive();
} else if (element.isJsonNull()) {
} else {
System.out.println("Error. Unknown type of element");
}
}
use code below code to convert your json string to generic java type List<Map<Object, Object>>, use code below.
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Test {
public static void main(String... args) {
String str = "[{'id':1,'name':'yogesh'},{'id':2,'name':'aarush', 'degree': 'MCA'}]";
Type type = new TypeToken<List<Map<Object, Object>>>() {
}.getType();
List<Map<Object, Object>> list = new Gson().fromJson(str, type);
System.out.println(new Gson().toJson(list));
filterList(list, "name", "yogesh");
System.out.println(new Gson().toJson(list));
}
public static void filterList(List<Map<Object, Object>> list, String key, Object value) {
for (Map<Object, Object> map : list) {
if (map.containsKey(key)) {
if (map.get(key).equals(value)) {
list.remove(map);
}
}
}
}
}
here i filterd name=yogesh record.
output:
[{"id":1.0,"name":"yogesh"},{"id":2.0,"name":"aarush","degree":"MCA"}]
[{"id":2.0,"name":"aarush","degree":"MCA"}]
I had similar issues and I googled, read a lot about this. In conclusion, the best(most efficient) way (with gson) is to write a custom TypeAdapter for your case.
You can test sample code below (it is working as you expected):
public static void answer() {
String jsonAsText = "{\"dataset\":[{\"album_id\":1,\"album_type\":\"Live Performance\",\"artist_name\":\"John Doe\"},{\"album_id\":2,\"album_type\":\"A Dummy Performance\"}]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(List.class, new AlbumInfoListTypeAdapter());
Gson gson = gsonBuilder.create();
List<AlbumInfo> dataSet = gson.fromJson(jsonAsText, List.class);
System.out.println(gson.toJson(dataSet));
}
private static class AlbumInfo {
int album_id;
String album_type;
String artist_name;
}
private static class AlbumInfoListTypeAdapter extends
TypeAdapter<List<AlbumInfo>> {
#Override
public List<AlbumInfo> read(com.google.gson.stream.JsonReader in)
throws IOException {
List<AlbumInfo> dataSet = new ArrayList<AlbumInfo>();
in.beginObject();
while (in.hasNext()) {
if ("dataset".equals(in.nextName())) {
in.beginArray();
while (in.hasNext()) {
in.beginObject();
AlbumInfo albumInfo = new AlbumInfo();
while (in.hasNext()) {
String jsonTag = in.nextName();
if ("album_id".equals(jsonTag)) {
albumInfo.album_id = in.nextInt();
} else if ("album_type".equals(jsonTag)) {
albumInfo.album_type = in.nextString();
} else if ("artist_name".equals(jsonTag)) {
albumInfo.artist_name = in.nextString();
}
}
in.endObject();
if (albumInfo.artist_name != null && !"".equals(albumInfo.artist_name.trim())) {
dataSet.add(albumInfo);
} else {
System.out.println("Album info ignored because it has no artist_name value");
}
}
in.endArray();
}
}
in.endObject();
return dataSet;
}
#Override
public void write(com.google.gson.stream.JsonWriter out,
List<AlbumInfo> dataSet) throws IOException {
out.beginObject();
out.name("dataset").beginArray();
for (final AlbumInfo albumInfo : dataSet) {
out.beginObject();
out.name("album_id").value(albumInfo.album_id);
out.name("album_type").value(albumInfo.album_type);
out.name("artist_name").value(albumInfo.artist_name);
out.endObject();
}
out.endArray();
out.endObject();
}
}
You can modify the read and the write methods. Gson has many cool functions. I strongly suggest you to read samples at this link.
Edit:
Incoming json text:
{
"dataset": [
{
"album_id": 1,
"album_type": "Live Performance",
"artist_name": "John Doe"
},
{
"album_id": 2,
"album_type": "A Dummy Performance"
}
]
}
The output at System.out.println at answer method:
[
{
"artist_name": "John Doe",
"album_type": "Live Performance",
"album_id": 1
}
]

Convert a JSON String to a HashMap

I'm using Java, and I have a String which is JSON:
{
"name" : "abc" ,
"email id " : ["abc#gmail.com","def#gmail.com","ghi#gmail.com"]
}
Then my Map in Java:
Map<String, Object> retMap = new HashMap<String, Object>();
I want to store all the data from the JSONObject in that HashMap.
Can anyone provide code for this? I want to use the org.json library.
In recursive way:
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;
}
Using Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, HashMap.class);
Using Gson, you can do the following:
Map<String, Object> retMap = new Gson().fromJson(
jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
Hope this will work, try this:
import com.fasterxml.jackson.databind.ObjectMapper;
Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class);
str, your JSON String
As Simple as this, if you want emailid,
String emailIds = response.get("email id").toString();
I just used Gson
HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);
Here is Vikas's code ported to JSR 353:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.json.JsonArray;
import javax.json.JsonException;
import javax.json.JsonObject;
public class JsonUtils {
public static Map<String, Object> jsonToMap(JsonObject json) {
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.keySet().iterator();
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) {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.size(); 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;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonUtils {
public static Map<String, Object> jsonToMap(JSONObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if(json != null) {
retMap = toMap(json);
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keySet().iterator();
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) {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.size(); 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;
}
}
try this code :
Map<String, String> params = new HashMap<String, String>();
try
{
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = (String) keys.next();
String value = jsonObject.getString(key);
params.put(key, value);
}
}
catch (Exception xx)
{
xx.toString();
}
Latest Update: I have used FasterXML Jackson Databind2.12.3 to Convert JSON string to Map, Map to JSON string.
// javax.ws.rs.core.Response clientresponse = null; // Read JSON with Jersey 2.0 (JAX-RS 2.0)
// String json_string = clientresponse.readEntity(String.class);
String json_string = "[\r\n"
+ "{\"domain\":\"stackoverflow.com\", \"userId\":5081877, \"userName\":\"Yash\"},\r\n"
+ "{\"domain\":\"stackoverflow.com\", \"userId\":6575754, \"userName\":\"Yash\"}\r\n"
+ "]";
System.out.println("Input/Response JSON string:"+json_string);
ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
//java.util.Map<String, String> map = mapper.readValue(json_string, java.util.Map.class);
List<Map<String, Object>> listOfMaps = mapper.readValue(json_string, new com.fasterxml.jackson.core.type.TypeReference< List<Map<String, Object>>>() {});
System.out.println("fasterxml JSON string to List of Map:"+listOfMaps);
String json = mapper.writeValueAsString(listOfMaps);
System.out.println("fasterxml List of Map to JSON string:[compact-print]"+json);
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(listOfMaps);
System.out.println("fasterxml List of Map to JSON string:[pretty-print]"+json);
output:
Input/Response JSON string:[
{"domain":"stackoverflow.com", "userId":5081877, "userName":"Yash"},
{"domain":"stackoverflow.com", "userId":6575754, "userName":"Yash"}
]
fasterxml JSON string to List of Map:[{domain=stackoverflow.com, userId=5081877, userName=Yash}, {domain=stackoverflow.com, userId=6575754, userName=Yash}]
fasterxml List of Map to JSON string:[compact-print][{"domain":"stackoverflow.com","userId":5081877,"userName":"Yash"},{"domain":"stackoverflow.com","userId":6575754,"userName":"Yash"}]
fasterxml List of Map to JSON string:[pretty-print][ {
"domain" : "stackoverflow.com",
"userId" : 5081877,
"userName" : "Yash"
}, {
"domain" : "stackoverflow.com",
"userId" : 6575754,
"userName" : "Yash"
} ]
Converting a JSON String to Map
public static java.util.Map<String, Object> jsonString2Map( String jsonString ) throws org.json.JSONException {
Map<String, Object> keys = new HashMap<String, Object>();
org.json.JSONObject jsonObject = new org.json.JSONObject( jsonString ); // HashMap
java.util.Iterator<?> keyset = jsonObject.keys(); // HM
while (keyset.hasNext()) {
String key = (String) keyset.next();
Object value = jsonObject.get(key);
System.out.print("\n Key : "+key);
if ( value instanceof org.json.JSONObject ) {
System.out.println("Incomin value is of JSONObject : ");
keys.put( key, jsonString2Map( value.toString() ));
} else if ( value instanceof org.json.JSONArray) {
org.json.JSONArray jsonArray = jsonObject.getJSONArray(key);
//JSONArray jsonArray = new JSONArray(value.toString());
keys.put( key, jsonArray2List( jsonArray ));
} else {
keyNode( value);
keys.put( key, value );
}
}
return keys;
}
Converting JSON Array to List
public static java.util.List<Object> jsonArray2List( org.json.JSONArray arrayOFKeys ) throws org.json.JSONException {
System.out.println("Incoming value is of JSONArray : =========");
java.util.List<Object> array2List = new java.util.ArrayList<Object>();
for ( int i = 0; i < arrayOFKeys.length(); i++ ) {
if ( arrayOFKeys.opt(i) instanceof org.json.JSONObject ) {
Map<String, Object> subObj2Map = jsonString2Map(arrayOFKeys.opt(i).toString());
array2List.add(subObj2Map);
} else if ( arrayOFKeys.opt(i) instanceof org.json.JSONArray ) {
java.util.List<Object> subarray2List = jsonArray2List((org.json.JSONArray) arrayOFKeys.opt(i));
array2List.add(subarray2List);
} else {
keyNode( arrayOFKeys.opt(i) );
array2List.add( arrayOFKeys.opt(i) );
}
}
return array2List;
}
public static Object keyNode(Object o) {
if (o instanceof String || o instanceof Character) return (String) o;
else if (o instanceof Number) return (Number) o;
else return o;
}
Display JSON of Any Format
public static void displayJSONMAP( Map<String, Object> allKeys ) throws Exception{
Set<String> keyset = allKeys.keySet(); // HM$keyset
if (! keyset.isEmpty()) {
Iterator<String> keys = keyset.iterator(); // HM$keysIterator
while (keys.hasNext()) {
String key = keys.next();
Object value = allKeys.get( key );
if ( value instanceof Map ) {
System.out.println("\n Object Key : "+key);
displayJSONMAP(jsonString2Map(value.toString()));
}else if ( value instanceof List ) {
System.out.println("\n Array Key : "+key);
JSONArray jsonArray = new JSONArray(value.toString());
jsonArray2List(jsonArray);
}else {
System.out.println("key : "+key+" value : "+value);
}
}
}
}
Google.gson to HashMap.
Convert using Jackson :
JSONObject obj = new JSONObject().put("abc", "pqr").put("xyz", 5);
Map<String, Object> map = new ObjectMapper().readValue(obj.toString(), new TypeReference<Map<String, Object>>() {});
You can convert any JSON to map by using Jackson library as below:
String json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"abc#gmail.com\",\"def#gmail.com\",\"ghi#gmail.com\"]\r\n}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
System.out.println(map);
Maven Dependencies for Jackson :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
Hope this will help. Happy coding :)
You can use Jackson API as well for this :
final String json = "....your json...";
final ObjectMapper mapper = new ObjectMapper();
final MapType type = mapper.getTypeFactory().constructMapType(
Map.class, String.class, Object.class);
final Map<String, Object> data = mapper.readValue(json, type);
If you hate recursion - using a Stack and javax.json to convert a Json String into a List of Maps:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.json.Json;
import javax.json.stream.JsonParser;
public class TestCreateObjFromJson {
public static List<Map<String,Object>> extract(InputStream is) {
List extracted = new ArrayList<>();
JsonParser parser = Json.createParser(is);
String nextKey = "";
Object nextval = "";
Stack s = new Stack<>();
while(parser.hasNext()) {
JsonParser.Event event = parser.next();
switch(event) {
case START_ARRAY : List nextList = new ArrayList<>();
if(!s.empty()) {
// If this is not the root object, add it to tbe parent object
setValue(s,nextKey,nextList);
}
s.push(nextList);
break;
case START_OBJECT : Map<String,Object> nextMap = new HashMap<>();
if(!s.empty()) {
// If this is not the root object, add it to tbe parent object
setValue(s,nextKey,nextMap);
}
s.push(nextMap);
break;
case KEY_NAME : nextKey = parser.getString();
break;
case VALUE_STRING : setValue(s,nextKey,parser.getString());
break;
case VALUE_NUMBER : setValue(s,nextKey,parser.getLong());
break;
case VALUE_TRUE : setValue(s,nextKey,true);
break;
case VALUE_FALSE : setValue(s,nextKey,false);
break;
case VALUE_NULL : setValue(s,nextKey,"");
break;
case END_OBJECT :
case END_ARRAY : if(s.size() > 1) {
// If this is not a root object, move up
s.pop();
} else {
// If this is a root object, add ir ro rhw final
extracted.add(s.pop());
}
default : break;
}
}
return extracted;
}
private static void setValue(Stack s, String nextKey, Object v) {
if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
else ((List)s.peek()).add(v);
}
}
There’s an older answer using javax.json posted here, however it only converts JsonArray and JsonObject, but there are still JsonString, JsonNumber, and JsonValue wrapper classes in the output. If you want to get rid of these, here’s my solution which will unwrap everything.
Beside that, it makes use of Java 8 streams and is contained in a single method.
/**
* Convert a JsonValue into a “plain” Java structure (using Map and List).
*
* #param value The JsonValue, not <code>null</code>.
* #return Map, List, String, Number, Boolean, or <code>null</code>.
*/
public static Object toObject(JsonValue value) {
Objects.requireNonNull(value, "value was null");
switch (value.getValueType()) {
case ARRAY:
return ((JsonArray) value)
.stream()
.map(JsonUtils::toObject)
.collect(Collectors.toList());
case OBJECT:
return ((JsonObject) value)
.entrySet()
.stream()
.collect(Collectors.toMap(
Entry::getKey,
e -> toObject(e.getValue())));
case STRING:
return ((JsonString) value).getString();
case NUMBER:
return ((JsonNumber) value).numberValue();
case TRUE:
return Boolean.TRUE;
case FALSE:
return Boolean.FALSE;
case NULL:
return null;
default:
throw new IllegalArgumentException("Unexpected type: " + value.getValueType());
}
}
You can use google gson library to convert json object.
https://code.google.com/p/google-gson/‎
Other librarys like Jackson are also available.
This won't convert it to a map. But you can do all things which you want.
Brief and Useful:
/**
* #param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
* a <code>Boolean</code>, a <code>Number</code>,
* a <code>null</code> or a <code>JSONObject.NULL</code>.
* #return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
* a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
*/
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
if (jsonThing instanceof JSONArray) {
final ArrayList<Object> list = new ArrayList<>();
final JSONArray jsonArray = (JSONArray) jsonThing;
final int l = jsonArray.length();
for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i)));
return list;
}
if (jsonThing instanceof JSONObject) {
final HashMap<String, Object> map = new HashMap<>();
final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
while (keysItr.hasNext()) {
final String key = keysItr.next();
map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
}
return map;
}
if (JSONObject.NULL.equals(jsonThing)) return null;
return jsonThing;
}
Thank #Vikas Gupta.
The following parser reads a file, parses it into a generic JsonElement, using Google's JsonParser.parse method, and then converts all the items in the generated JSON into a native Java List<object> or Map<String, Object>.
Note: The code below is based off of Vikas Gupta's answer.
GsonParser.java
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
public class GsonParser {
public static void main(String[] args) {
try {
print(loadJsonArray("data_array.json", true));
print(loadJsonObject("data_object.json", true));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void print(Object object) {
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object).toString());
}
public static Map<String, Object> loadJsonObject(String filename, boolean isResource)
throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
return jsonToMap(loadJson(filename, isResource).getAsJsonObject());
}
public static List<Object> loadJsonArray(String filename, boolean isResource)
throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
return jsonToList(loadJson(filename, isResource).getAsJsonArray());
}
private static JsonElement loadJson(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException {
return new JsonParser().parse(new InputStreamReader(FileLoader.openInputStream(filename, isResource), "UTF-8"));
}
public static Object parse(JsonElement json) {
if (json.isJsonObject()) {
return jsonToMap((JsonObject) json);
} else if (json.isJsonArray()) {
return jsonToList((JsonArray) json);
}
return null;
}
public static Map<String, Object> jsonToMap(JsonObject jsonObject) {
if (jsonObject.isJsonNull()) {
return new HashMap<String, Object>();
}
return toMap(jsonObject);
}
public static List<Object> jsonToList(JsonArray jsonArray) {
if (jsonArray.isJsonNull()) {
return new ArrayList<Object>();
}
return toList(jsonArray);
}
private static final Map<String, Object> toMap(JsonObject object) {
Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, JsonElement> pair : object.entrySet()) {
map.put(pair.getKey(), toValue(pair.getValue()));
}
return map;
}
private static final List<Object> toList(JsonArray array) {
List<Object> list = new ArrayList<Object>();
for (JsonElement element : array) {
list.add(toValue(element));
}
return list;
}
private static final Object toPrimitive(JsonPrimitive value) {
if (value.isBoolean()) {
return value.getAsBoolean();
} else if (value.isString()) {
return value.getAsString();
} else if (value.isNumber()){
return value.getAsNumber();
}
return null;
}
private static final Object toValue(JsonElement value) {
if (value.isJsonNull()) {
return null;
} else if (value.isJsonArray()) {
return toList((JsonArray) value);
} else if (value.isJsonObject()) {
return toMap((JsonObject) value);
} else if (value.isJsonPrimitive()) {
return toPrimitive((JsonPrimitive) value);
}
return null;
}
}
FileLoader.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileLoader {
public static Reader openReader(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
return openReader(filename, isResource, "UTF-8");
}
public static Reader openReader(String filename, boolean isResource, String charset) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException {
return new InputStreamReader(openInputStream(filename, isResource), charset);
}
public static InputStream openInputStream(String filename, boolean isResource) throws FileNotFoundException, MalformedURLException {
if (isResource) {
return FileLoader.class.getClassLoader().getResourceAsStream(filename);
}
return new FileInputStream(load(filename, isResource));
}
public static String read(String path, boolean isResource) throws IOException {
return read(path, isResource, "UTF-8");
}
public static String read(String path, boolean isResource, String charset) throws IOException {
return read(pathToUrl(path, isResource), charset);
}
#SuppressWarnings("resource")
protected static String read(URL url, String charset) throws IOException {
return new Scanner(url.openStream(), charset).useDelimiter("\\A").next();
}
protected static File load(String path, boolean isResource) throws MalformedURLException {
return load(pathToUrl(path, isResource));
}
protected static File load(URL url) {
try {
return new File(url.toURI());
} catch (URISyntaxException e) {
return new File(url.getPath());
}
}
private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException {
if (isResource) {
return FileLoader.class.getClassLoader().getResource(path);
}
return new URL("file:/" + path);
}
}
If you want no-lib version, here is the solution with regex:
public static HashMap<String, String> jsonStringToMap(String inputJsonString) {
final String regex = "(?:\\\"|\\')(?<key>[\\w\\d]+)(?:\\\"|\\')(?:\\:\\s*)(?:\\\"|\\')?(?<value>[\\w\\s-]*)(?:\\\"|\\')?";
HashMap<String, String> map = new HashMap<>();
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(inputJsonString);
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
map.put(matcher.group("key"), matcher.group("value"));
}
}
return map;
}
Imagine u have a list of email like below. not constrained to any programming language,
emailsList = ["abc#gmail.com","def#gmail.com","ghi#gmail.com"]
Now following is JAVA code - for converting json to map
JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();
This is an old question and maybe still relate to someone.
Let's say you have string HashMap hash and JsonObject jsonObject.
1) Define key-list.
Example:
ArrayList<String> keyArrayList = new ArrayList<>();
keyArrayList.add("key0");
keyArrayList.add("key1");
2) Create foreach loop, add hash from jsonObject with:
for(String key : keyArrayList){
hash.put(key, jsonObject.getString(key));
}
That's my approach, hope it answer the question.
Using json-simple you can convert data JSON to Map and Map to JSON.
try
{
JSONObject obj11 = new JSONObject();
obj11.put(1, "Kishan");
obj11.put(2, "Radhesh");
obj11.put(3, "Sonal");
obj11.put(4, "Madhu");
Map map = new HashMap();
obj11.toJSONString();
map = obj11;
System.out.println(map.get(1));
JSONObject obj12 = new JSONObject();
obj12 = (JSONObject) map;
System.out.println(obj12.get(1));
}
catch(Exception e)
{
System.err.println("EROR : 01 :"+e);
}

Categories