Search code examples
javahashmapjava-stream

Java return nested hashmap as string formatted as Json using Streams API


I have a nested HashMap declared as Map<String, Object>.

Map<String,Object> m1 = new HashMap<>();
        m1.put("name","mary");
        m1.put("email","mary@email.com");
        m1.put("address", new HashMap<>() {{
            put("firstLine", "101 Oracle");
            put("zipCode", "java 20");
        }});

I want to return this as a String in the following way without the help of an external library:

{
address : {
zipCode : Java 20,
firstLine : 101 Oracle
},
name : mary,
email : mary@mail.com
}

I cannot format the nested map in the way I want. So far I have this:

String s = m1.entrySet().stream()
                        .map(e -> e.getKey() + " : " + e.getValue())
                        .collect(Collectors.joining(", " + "\n", "{" + "\n", "\n" + "}"));
System.out.println(s);

Which gives me:

{
address : {zipCode=java 20, firstLine=101 Oracle}, 
name : mary, 
email : mary@email.com
}

Solution

  • import java.util.Map;
    
    public class JsonConverter {
        public static String mapToJsonString(Map<String, Object> map) {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
    
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
    
                sb.append("\"").append(key).append("\"").append(" : ");
    
                if (value instanceof Map) {
                    // Recursively convert nested Map to JSON
                    sb.append(mapToJsonString((Map<String, Object>) value));
                } else if (value instanceof String) {
                    sb.append("\"").append(value).append("\"");
                } else {
                    sb.append(value);
                }
    
                sb.append(", ");
            }
    
            // Remove the trailing comma and space
            if (sb.length() > 1) {
                sb.setLength(sb.length() - 2);
            }
    
            sb.append("}");
            return sb.toString();
        }
    
        public static void main(String[] args) {
            Map<String, Object> m1 = new HashMap<>();
            m1.put("name", "mary");
            m1.put("email", "mary@email.com");
            m1.put("address", new HashMap<>() {{
                put("firstLine", "101 Oracle");
                put("zipCode", "java 20");
            }});
    
            String jsonString = mapToJsonString(m1);
            System.out.println(jsonString);
        }
    }