Wednesday, March 1, 2017

Object to JSON string mapper in JAVA

Following code can be used to convert JAVA objects to JSON string. You have to use jackson JAVA library for objects to JSON conversion.

RequestMessage requestMessage = new RequestMessage();
        RequestEntity requestEntity = new RequestEntity();
        requestEntity.setAccountNo("1234");
        requestEntity.setBillNo("9876");
        requestEntity.setType("S");
        requestMessage.setRequestEntity(requestEntity);

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(requestMessage)); 

Converted JSONstring will like this.

{"requestEntity":{"billNo":"9876","accountNo":"1234","type":"S"}}