使用Jackson将地图转换为JSON [英] Convert Map to JSON using Jackson
本文介绍了使用Jackson将地图转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用Jackson将地图转换为有效的JSON?
我正在使用Google的GSON通过Spring Boot REST Post方法执行此操作...
p>以下是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);
$ b $ p
$ b $ p所以,当我使用它调用它时: p>
curl -HAccept:application / json-HContent-type:application / json\
- X POST -d'{name:value}'http:// localhost:8080 / myservice / validate
将以下内容接收到stdout(这正是我想要的):
{name:value }
是否有更好的方式使用Jackson来代替Google的Gson和/或我你可以转换 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);
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?
解决方案 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);
这篇关于使用Jackson将地图转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文