将Jackson对象转换为JSONObject java

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)

Sot*_*lis 6

现在,您将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)

它非常易于使用。

  • 这是不对的。但是有时候当您要处理真正的旧代码库时。我正在搬到杰克逊,但仍然有很多使用JsonObject的旧代码。而且现在不必总是有时间重写并可能破坏无数行。感谢您的答案@MacDaddy (4认同)