-3

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?

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
himan
  • 19
  • 1
  • 6

1 Answers1

2

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"
}
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
  • Good answer, but if we're still within a Spring Boot context when a manual serialization is needed, a simpler way is to just pull in the auto-configured ObjectMapper bean, and supply the object to be serialized (Map in this case) to its `writeValueAsString` method. Then again, it's an "external library", so... – cpigeon Oct 21 '22 at 13:52
  • @cpigeon Thanks for your comment. As I've said in the first part of the answer, that's the default behavior, i.e. there's nothing to configure, the map would be serialized precisely like that. The code provided in the second part just tackles what OP was asking for *"get the equivalent json string using only java inbuilt methods"* (I would **not** recommend generating JSON manually regardless whether the Spring is used in the project or not). – Alexander Ivanchenko Oct 21 '22 at 14:27
  • @cpigeon Regarding the ways of tweaking the serialization with Spring Boot, I agree that we should rely on the built-in mechanisms. I would advise doing customizations without accessing `ObjectMapper` directly (unless you didn't find other way), for instance via `Jackson2ObjectMapperBuilderCustomizer` Bean. Or in the case if you only need to plug-in the module (like `JavaTimeModule`) it would be sufficient to put the module as a Bean in the Context and Spring Boot will do all the required configuration steps. – Alexander Ivanchenko Oct 21 '22 at 14:38