我想在以下代码片段上用Jackson替换JSON.simple:
JSONObject request = new JSONObject();
request.put("String key", /String value/);
request.put("String key", /int value/);
...
看起来像这样:
ObjectMapper mapper = new ObjectMapper();
JsonNode request = mapper.createObjectNode();
((ObjectNode) request).put("String key", /String value/);
((ObjectNode) request).put("String key", /int value/);
我发现强制转换和多余的声明有点过于复杂和丑陋。我有做错什么建议吗?
(我想通过REST实体发送此JSON)
答案 0 :(得分:1)
使用ObjectNode代替JsonNode。试试这个:
ObjectNode request = mapper.createObjectNode();
request.put("key", "val");
System.out.println(request.toString());
答案 1 :(得分:0)
此链接提供了很好的信息。我觉得您应该拥有对象,而不是手动构建json。
https://www.baeldung.com/jackson-object-mapper-tutorial
public class Car {
private String color;
private String type;
// standard getters setters
}
然后
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
String output = objectMapper.writeValueAsString(car);
输出:
{"color":"yellow","type":"renault"}
答案 2 :(得分:0)
您的代码应该是这样
ObjectMapper mapper = new ObjectMapper();
ObjectNode request = mapper.createObjectNode();
request.put("String key", /String value/);
request.put("String key", /int value/);