himan
himan

Reputation: 19

Convert a HashMap to JSON String using only built-in methods with Java 8

I have a json options

options = {
  "access": "public"
}

Have made it in java using Hashmap, as shown below:

Map<String, String> options = new LinkedHashMap<String, String>();
options.put("access", "public");

Now I want to convert this to json string, something like below:

optionsString = "{\"access\":\"public\"}"

I know we can do it with external libraries like gson, jackson, jsonObject, etc.

But I wanted to get the equivalent json string using only java inbuilt methods and no external libraries.

Is there any way to accomplish this?

Upvotes: -3

Views: 1005

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29038

But I wanted to get the equivalent json string using only java inbuilt methods and no external libraries.

Since you're using Spring, that intention is weird.

Jackson library is already integrated with Spring, it's coming with Spring Web dependency. Spring Boot would autoconfigure it at the application start up. And would be used automatically to deserialize JSON requests into proper objects and to convert objects into JSON.

If you return a Map from a method of a rest-controller, it would be serialized into JSON without any effort from your side.

That's how such endpoint might look like:

@GetMapping(path = "/foo")
public Map<String, String> bar() {
    
    Map<String, String> options = // initialize the map 
        
    return options;
}

But if you really want to convert a simple Map containing pairs attribute-value into JSON manually, here's how it can be done in a single statement with Stream API using collector Collectors.joining():

public static String mapToJson(Map<String, String> map) {
    
    return map.entrySet().stream()
        .map(e -> String.format("\t\"%s\":\"%s\"", e.getKey(), e.getValue()))
        .collect(Collectors.joining(",\n", "{\n", "\n}"));
}

main()

public static void main(String[] args) {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("access", "public");
    options.put("foo", "bar");

    System.out.println(mapToJson(options));
}

Output:

{
    "access":"public",
    "foo":"bar"
}

Upvotes: 2

Related Questions