From org.json JSONObject to org.codehaus.jackson

后端 未结 3 2061
故里飘歌
故里飘歌 2021-02-05 23:10

I want to move from org.json to org.codehaus.jackson. How do I convert the following Java code?

private JSONObject myJsonMessage(String         


        
3条回答
  •  遥遥无期
    2021-02-05 23:36

    There is no JSONObject in Jackson api. Rather than returning a JSONObject, you can either return a Map or a Java Bean with message property that has getters and setters for it.

    public class MyMessage {
        private String message;
    
        public void setMessage(final String message) {
            this.message = message;
        }
    
        public String getMessage() {
            return this.message;
        }
    }
    

    So, your method will be reduced to:

    private MyMessage(String message) {
        MyMessage myMessage = new MyMessage();
        myMessage.setMessage(message);
        return myMessage;
    }
    

    Another aspect of this change would be changing the serialization code, to convert MyMessage back to json string. Jackson does Java Beans, maps by default, you don't need to create a JSONObject e.g.,

    private String serializeMessage(MyMessage message){
    
        //Note: you probably want to put it in a global converter and share the object mapper
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(message);
    }
    

    The above will return {message: "some message"}

    I have skipped the exceptions for brevity.

提交回复
热议问题