How to convert hashmap to JSON object in Java
You can use:
new JSONObject(map);
Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html
Converting Map to JSONObject
What you want to do is simply:
jsonMap.put("testAtts", new JSONObject(testAttMap));
instead of
jsonMap.put("testAtts", new JSONObject(testAttMap).toString());
the slashes are there because you are escaping the double quotes
How to properly convert HashMap String,List Object to Json with array of json object
It is now working using these changes:
HashMap<String,List<Object>> responses = new HashMap<String,List<Object>>();
for (ConsumerRecord<String,String> consumerRecord : records) {
if(!responses.containsKey(consumerRecord.topic())){
responses.put(consumerRecord.topic(), new ArrayList<Object>());
}
responses.get(consumerRecord.topic()).add(new JSONObject(consumerRecord.value()));
}
jsonObject = new JSONObject(responses);
return jsonObject.toMap();
- Convert Kafka message string to JSONObject
new JSONObject(consumerRecord.value())
- Construct a JSONObject from a Map using
jsonObject = new JSONObject(responses);
- Return Map<String, Object> using
jsonObject.toMap();
How to convert HashMap to JsonObject directly
Gson gson = new Gson();
gson.toJsonTree(hashmap).getAsJsonObject();
This is what I was able to glean from reading the API
It seems to me you want to use the .toJsonTree method instead of the .toJson method and then get the JsonElement as a JsonObject
Convert HashMap to JSON string using elemental.json.* classes
This is my current solution for converting to and from HashMap<String, Object>
. When a RunTimeException is thrown for a new type that is not yet catered for, I add it in.
public static String hashMapToJsonString(HashMap hashMap){
JsonObject json = hashMapToJsonObject(hashMap);
return new json.toJson();
}
public static HashMap<String, Object> jsonStringToHashMap(String string) {
JsonObject json = Json.parse(string.getRawString());
HashMap<String, Object> retMap = new HashMap<String, Object>();
if (!(json instanceof JreJsonNull)) {
retMap = jsonObjectToHashMap(json);
}
return retMap;
}
private static JsonObject hashMapToJsonObject(HashMap hashMap) {
JsonObject json = Json.createObject();
Set<String> keySet = hashMap.keySet();
for(String key : keySet){
Object object = hashMap.get(key);
if(object instanceof ArrayList){
json.put(key, arrayListToJsonArray((ArrayList)object));
} else if(object instanceof HashMap){
json.put(key, hashMapToJsonObject((HashMap)object));
} else if(object instanceof String) {
json.put(key, (String)object);
} else {
throw new RuntimeException("Type not catered for java->json conversion (in HashMap): " + object.getClass().getName());
}
}
return json;
}
private static JsonArray arrayListToJsonArray(ArrayList array) {
JsonArray json = Json.createArray();
int i = 0;
for(Object object : array){
if(object instanceof ArrayList) {
json.set(i, arrayListToJsonArray((ArrayList)object));
} else if(object instanceof HashMap) {
json.set(i, hashMapToJsonObject((HashMap)object));
} else if(object instanceof String) {
json.set(i, (String)object);
} else {
throw new RuntimeException("Type not catered for java->json conversion (in array): " + object.getClass().getName());
}
i ++;
}
return json;
}
private static HashMap<String, Object> jsonObjectToHashMap(JsonObject json) throws JsonException {
HashMap<String, Object> map = new HashMap<String, Object>();
String[] keys = json.keys();
for(String key : keys){
Object object = json.get(key);
map.put(key, jsonObjectToJavaObject(object));
}
return map;
}
private static ArrayList jsonArrayToArrayList(JsonArray json) throws JsonException {
ArrayList array = new ArrayList();
for(int i = 0; i < json.length(); i++) {
Object object = json.get(i);
array.add(jsonObjectToJavaObject(object));
}
return array;
}
private static Object jsonObjectToJavaObject(Object jsonObject) {
if(jsonObject instanceof JsonArray) {
return jsonArrayToArrayList((JsonArray) jsonObject);
} else if(jsonObject instanceof JsonObject) {
return jsonObjectToHashMap((JsonObject) jsonObject);
} else if(jsonObject instanceof JreJsonString) {
return ((JreJsonString)jsonObject).asString();
} else if(jsonObject instanceof JreJsonNumber) {
return new Double(((JreJsonNumber)jsonObject).asNumber());
} else if(jsonObject instanceof JreJsonNull){
return new Null();
} else {
throw new RuntimeException("Type not catered for json->java conversion: " + jsonObject.getClass().getName());
}
}
HashMap to Json Array Object - Java
You don't actually need to create a formal Java class to do this. We can try creating an ArrayNode
, and then adding child JsonNode
objects which represent each entry in your original hash map.
HashMap<String, Integer> worders = new HashMap<>();
worders.put("and", 100);
worders.put("the", 50);
ObjectMapper mapper = new ObjectMapper();
ArrayNode rootNode = mapper.createArrayNode();
for (Map.Entry<String, Integer> entry : worders.entrySet()) {
JsonNode childNode = mapper.createObjectNode();
((ObjectNode) childNode).put("word", entry.getKey());
((ObjectNode) childNode).put("count", entry.getValue());
((ArrayNode) rootNode).add(childNode);
}
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(jsonString);
Related Topics
How to Get the Current Date/Time in Java
Switch Tabs Using Selenium Webdriver with Java
How to Convert a Stack Trace to a String
What Is the Native Keyword in Java For
When Should a Class Be Comparable And/Or Comparator
Difference Between Thread's Context Class Loader and Normal Classloader
What Is the Java Equivalent for Linq
Implements VS Extends: When to Use? What's the Difference
How to Play .Wav Files with Java
What Is the Point of "Final Class" in Java
Is There a Performance Difference Between a for Loop and a For-Each Loop
Sorting a Collection of Objects
Java 8 Iterable.Foreach() VS Foreach Loop
String, Stringbuffer, and Stringbuilder
Why Is Hibernate Open Session in View Considered a Bad Practice
What Does the Java Assert Keyword Do, and When Should It Be Used
Differencebetween Instanceof and Class.Isassignablefrom(...)