Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a Java POJO to JSON string?

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

like image 964
Java Questions Avatar asked Feb 17 '23 19:02

Java Questions


1 Answers

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.

like image 143
hd1 Avatar answered Feb 28 '23 16:02

hd1