Question

I hava a POJO for which i set values, the pojo is:

public class CreateRequisitionRO extends AbstractPortfolioSpecificRO {

    private static final long serialVersionUID = 2418929142185068821L;

    private BigDecimal transSrlNo;
    private String transCode;
    private InflowOutflow inflowOutflow;

public BigDecimal getTransSrlNo() {
        return transSrlNo;
    }

    public void setTransSrlNo(BigDecimal transSrlNo) {
        this.transSrlNo = transSrlNo;
    }

    public InflowOutflow getInflowOutflow() {
        return inflowOutflow;
    }

    public void setInflowOutflow(InflowOutflow inflowOutflow) {
        this.inflowOutflow = inflowOutflow;
    }
    public String getTransCode() {
        return transCode;
    }
}

This is how i set values :

CreateRequisitionRO[] request = new CreateRequisitionRO[1];
    request[0].setTransSrlNo(new BigDecimal(1));
    request[0].setTransCode("BUY");
    request[0].setInflowOutflow(InflowOutflow.I);

now i would like to convert/serialize the above java pojo to Json string.

Could some body help me how to do this?

Best Regards

Was it helpful?

Solution

XStream or GSON, as mentioned in the other answer, will sort you. Follow the JSON tutorial on XStream and your code will look something like this:

        CreateRequisitionRO product = new CreateRequisitionRO();
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("product", Product.class);

        System.out.println(xstream.toXML(product));     

With GSON, your code will look like this:

CreateRequisitionRO obj = new CreateRequisitionRO();
Gson gson = new Gson();
String json = gson.toJson(obj); 

Pick your library and go.

OTHER TIPS

You can use the Gson libary to do the favor for you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top