将 Jackson 对象转换为 JSONObject java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22258487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Hymanson object into JSONObject java
提问by Code Junkie
I'm trying to figure out how to convert a Hymanson object into a JSONObject?
我想弄清楚如何将 Hymanson 对象转换为 JSONObject?
What I've tried, however I don't believe this is the correct approach.
我已经尝试过,但是我不相信这是正确的方法。
public JSONObject toJSON() throws IOException {
ObjectMapper mapper = new ObjectMapper();
return new JSONObject(mapper.writeValueAsString(new Warnings(warnings)));
}
回答by Sotirios Delimanolis
Right now, you are serializing your Pojo to a String
, then parsing that String
and converting it into a HashMap
style object in the form of JSONObject
.
现在,您正在将 Pojo 序列化为String
,然后对其进行解析String
并将其转换HashMap
为JSONObject
.
This is very inefficient and doesn't accomplish anything of benefit.
这是非常低效的,并没有完成任何有益的事情。
Hymanson already provides an ObjectNode
class for interacting with your Pojo as a JSON object. So just convert your object to an ObjectNode
. Here's a working example
Hymanson 已经提供了一个ObjectNode
类,用于作为 JSON 对象与您的 Pojo 交互。所以只需将您的对象转换为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;
}
}
Otherwise, the way you are doing it is fine.
否则,你这样做的方式很好。
回答by MacDaddy
The way you are doing is work fine, because i also use that way to make a JSONobject.
你这样做的方式很好,因为我也用这种方式来制作一个 JSONobject。
here is my code
这是我的代码
public JSONObject getRequestJson(AccountInquiryRequestVO accountInquiryRequestVO) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JSONObject jsonAccountInquiry;
jsonAccountInquiry=new JSONObject(mapper.writeValueAsString(accountInquiryRequestVO));
return jsonAccountInquiry;
}
its working fine for me. but you can always use JsonNode also here is the sample code for that
它对我来说工作正常。但你总是可以使用 JsonNode 也是这里的示例代码
JsonNode jsonNode=mapper.valueToTree(accountInquiryRequestVO);
its very easy to use.
它非常容易使用。