Search code examples
javajsonjacksonpojo

Jackson Complex Pojo


I've been trying to make this JSON a POJO so that I can marshal/unmarshal it at will but I'm having difficulty finding a way to do that part:

{
  "jsonrpc": "2.0",
  "method": "deploy",
  "params": {
    "type": 1,
    "chaincodeID": {
      "path": "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
    },
    "ctorMsg": {
      "args": [
        "init",
        "a",
        "1000",
        "b",
        "2000"
      ]
    },
    "secureContext": "lukas"
  },
  "id": 1
}

As you can see there is a " params " properties which have 2 objects inside one of which is a JSON array.

public class JsonPayload {
    private String jsonrpc;
    private String method;
    private ??? params;
    private int id;

    public JsonPayload(String jsonrpc, String method, ??? params, int id) {
        this.jsonrpc = jsonrpc;
        this.method = method;
        this.params = params;
        this.id = id;
    }

    public String getJsonrpc() {
        return jsonrpc;
    }

    public void setJsonrpc(String jsonrpc) {
        this.jsonrpc = jsonrpc;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public ??? getParams() {
        return params;
    }

    public void setParams(??? params) {
        this.params = params;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

My question is how to model the Params inside the POJO. I guess I could create 2 more objects and pass them to it but that make it a lot more complex than I wish a simple JSON marshaling / unmarshaling would be.

Is there a simple way to do that? With or without Jackson?


Solution

  • This is how the Param POJO would look like, if you wish to model it (getters and setters excluded):

    class Params {
        Integer type;
        @JsonProperty("chaincodeID")
        ChainCode chainCode;
        @JsonProperty("ctorMsg")
        private Message message;
        String secureContext;
    }
    
    class ChainCode{
        String path;
    }
    
    class Message {
        List<String> args;
    }
    

    If you are not planning to use params at all or you don't care about the type then you can either use @JsonIgnoreProperties for base class or define params as Map<String, Object>