Cod*_*kie 11 java json jackson
我想弄清楚如何将Jackson对象转换为JSONObject?
我尝试了什么,但我不相信这是正确的方法.
public JSONObject toJSON() throws IOException {
ObjectMapper mapper = new ObjectMapper();
return new JSONObject(mapper.writeValueAsString(new Warnings(warnings)));
}
Run Code Online (Sandbox Code Playgroud)
现在,您将Pojo序列化为a String,然后解析String并将其转换为HashMap样式对象的形式JSONObject.
这是非常低效的,并没有实现任何好处.
杰克逊已经提供了一个ObjectNode与您的Pojo作为JSON对象进行交互的类.所以只需将您的对象转换为ObjectNode.这是一个有效的例子
public class Example {
public static void main(String[] args) throws Exception {
Pojo pojo = new Pojo();
pojo.setAge(42);
pojo.setName("Sotirios");
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.valueToTree(pojo);
System.out.println(node);
}
}
class Pojo {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Run Code Online (Sandbox Code Playgroud)
否则,你这样做的方式很好.
小智 5
您正在做的方式工作正常,因为我也使用这种方式来制作JSONobject。
这是我的代码
public JSONObject getRequestJson(AccountInquiryRequestVO accountInquiryRequestVO) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JSONObject jsonAccountInquiry;
jsonAccountInquiry=new JSONObject(mapper.writeValueAsString(accountInquiryRequestVO));
return jsonAccountInquiry;
}
Run Code Online (Sandbox Code Playgroud)
它对我来说很好。但您始终可以使用JsonNode,这也是该示例代码
JsonNode jsonNode=mapper.valueToTree(accountInquiryRequestVO);
Run Code Online (Sandbox Code Playgroud)
它非常易于使用。
| 归档时间: |
|
| 查看次数: |
33743 次 |
| 最近记录: |