Search code examples
javajsonobjectmappermapper

Return object as Json in java


We would like to return Object class as JSON string

 public static String genJson(Response r, Auth auth) {
            Auth p = new Auth();
            ObjectMapper mapper = new ObjectMapper();

            String transactionResult = r.getTransactionResult();
            if (transactionResult.equalsIgnoreCase("APPROVED")) {
                p.setPay_resp_resp_code("00");
                p.setPay_resp_desc("Waiting");

                try {
                    jsonStr = mapper.writeValueAsString(p);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
            return jsonStr;
        }

In Auth class, I have five variables, but I only want it to display two, which are resp_code and resp_desc. But the above code always return 5 variables.

Edit

This is how our code suppose to work. First it will convert jsonString to object class named Auth. Then it will execute the if statement.

 @RequestMapping("/authstep")
    @ResponseBody
    private String AuthRequest(@RequestBody String jsonString) {

        log.info("========== Receive JSON object request ==========");

        if (jsonString != null) {

            Auth auth = new Auth();

            ObjectMapper mapper = new ObjectMapper();
            try {
                auth = mapper.readValue(jsonString, Auth.class);
            } catch (JsonGenerationException jge) {
                jge.printStackTrace();
            } catch (JsonMappingException jme) {
                jme.printStackTrace();
            } catch (JsonParseException jpe) {
                jpe.printStackTrace();
            } catch (IOException io) {
                io.printStackTrace();
            }

            if (auth.getSignature().equals(signature)) {
               Response response =xxx.getStep(auth);
               return Util.genJson(response, auth);
            }              
        }
        return null;
    }

Auth

@Data
public class Auth {

    @JsonIgnore
    private String cipher;

    @JsonIgnore
    private String month;

    @JsonIgnore
    private String signature;

    // need to return these two as json
    private String pay_resp_resp_code;
    private String pay_resp_desc;

}

After add @JsonIgnore, signature become null


Solution

  • If you are using jackson 1.9 below version

      Add @IgnoreJson annotation on Getter method
    

    If you are using newer version of jackson

    @JsonProperty(access = Access.WRITE_ONLY) 
    private String password;