使用Jackson将Map转换为JSON

时间:2015-03-30 07:18:25

标签: java json spring jackson gson

如何使用Jackson将Map转换为有效的JSON?

我是通过Spring Boot REST Post方法使用Google的GSON进行的...

这是RESTful Web服务:

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

所以,当我使用它调用它时:

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

将以下内容发送到标准输出(这正是我想要的):

{"name":"value"}

有没有更好的方法来使用杰克逊代替谷歌的Gson和/或我是否完全以错误的方式解决这个问题?

4 个答案:

答案 0 :(得分:72)

您可以使用Jackson将Map转换为JSON,如下所示:

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

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

答案 1 :(得分:1)

您应该更喜欢Object Mapper。以下是相同的链接:Object Mapper - Spring MVC way of Obect to JSON

答案 2 :(得分:1)

使用jackson,你可以这样做:

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

答案 3 :(得分:0)

如果你正在使用jackson,最好直接转换为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;
}