Convert Map to JSON using Jackson

PacificNW_Lover picture PacificNW_Lover · Mar 30, 2015 · Viewed 103.3k times · Source

How can I convert a Map to a valid JSON using Jackson?

I am doing it using Google's GSON via a Spring Boot REST Post method...

Here's the RESTful Web Service:

import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.google.gson.Gson;

@RestController
@RequestMapping("/myservice")
public class ValidationService {    

    @RequestMapping(value="/validate", method = RequestMethod.POST)
    public void validate(@RequestBody Map<String, Object> payload) throws Exception {
        Gson gson = new Gson();
        String json = gson.toJson(payload); 
        System.out.println(json);
    }
}

So, when I invoke it using this:

curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/validate

Receive the following to stdout (this is exactly what I want):

{"name":"value"}

Is there a better way to do this using Jackson instead of Google's Gson and / or am I going about it the wrong way altogether?

Answer

Mithun picture Mithun · Mar 30, 2015

You can convert Map to JSON using Jackson as follows:

Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");

String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);