How to Convert Hashmap to JSON Object in Java

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();

  1. Convert Kafka message string to JSONObject new JSONObject(consumerRecord.value())
  2. Construct a JSONObject from a Map using
    jsonObject = new JSONObject(responses);
  3. 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



Leave a reply



Submit