Convert Map to JSON using Jackson

JavaJsonSpringJacksonGson

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

Using jackson, you can do it as follows:

    ObjectMapper mapper = new ObjectMapper();
    String clientFilterJson = "";
    try {
        clientFilterJson = mapper.writeValueAsString(filterSaveModel);
    } catch (IOException e) {
        e.printStackTrace();
    }

Solution 3 - Java

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

Solution 4 - Java

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPacificNW_LoverView Question on Stackoverflow
Solution 1 - JavaMithunView Answer on Stackoverflow
Solution 2 - JavaUzairView Answer on Stackoverflow
Solution 3 - JavaArpit AggarwalView Answer on Stackoverflow
Solution 4 - JavasebsterView Answer on Stackoverflow