69

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?

PacificNW_Lover
  • 4,746
  • 31
  • 90
  • 144
  • possible duplicate of [Jackson Vs. Gson](http://stackoverflow.com/questions/2378402/jackson-vs-gson) – Neeraj Jain Mar 30 '15 at 07:24
  • 6
    Neeraj Jain, Thanks for the comment but: Jackson vs. Gson is about the positives and negatives of Jackson vs. Gson. This post is a specific question. – PacificNW_Lover Mar 30 '15 at 07:43

4 Answers4

147

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);
Mithun
  • 7,747
  • 6
  • 52
  • 68
  • 6
    This is Map to String, not JSON. There will be another step to convert output string to JSON type. – Nayan Wadekar Jun 29 '16 at 14:03
  • 1
    @NayanWadekar this actually works, I think you are mistaken or maybe you'd like to provide some insight? – Bruno Bossola Aug 25 '16 at 16:09
  • 1
    @BrunoBossola Sorry, I was thinking about actual JSON object, didn't saw the output required, for JSON string representation, this is correct. – Nayan Wadekar Sep 02 '16 at 11:53
  • @Mithun Is this efficient in case you want to do this million times? My program goes out of memory, maybe Objectmapper is holding on to a lot of memory while converting these objects? – lucifer Jan 07 '20 at 06:40
  • it throws erro unreported exception com.fasterxml.jackson.core.JsonProcessingException; must be caught or declared to be thrown – Amrit Aug 19 '20 at 13:11
  • @Mithun, Will it work if my map is like this? Map snsMessage = new HashMap<>(); – Deva Sep 03 '20 at 13:08
9

Using jackson, you can do it as follows:

    ObjectMapper mapper = new ObjectMapper();
    String clientFilterJson = "";
    try {
        clientFilterJson = mapper.writeValueAsString(filterSaveModel);
    } catch (IOException e) {
        e.printStackTrace();
    }
Uzair
  • 1,529
  • 14
  • 17
  • Will it work if my map is like this? Map snsMessage = new HashMap<>(); – Deva Sep 03 '20 at 13:07
  • @Deva ensure that your Objects are not recursive; you made need to mark the reentrant object pointers with Exclude to break the recursion. – Jack Punt Nov 10 '22 at 21:33
1

You should prefer Object Mapper instead. Here is the link for the same : Object Mapper - Spring MVC way of Obect to JSON

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
1

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}
sebster
  • 1,322
  • 2
  • 18
  • 29