简体   繁体   English

如何将Java POJO转换为JSON字符串?

[英]how to convert a Java POJO to JSON string?

I hava a POJO for which i set values, the pojo is: 我有一个POJO为我设定值,pojo是:

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 最好的祝福

XStream or GSON , as mentioned in the other answer, will sort you. 如其他答案中所述, XStreamGSON将对您进行排序。 Follow the JSON tutorial on XStream and your code will look something like this: 按照XStream上JSON教程 ,您的代码将如下所示:

        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 : 使用GSON,您的代码将如下所示

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

Pick your library and go. 选择你的图书馆然后去。

您可以使用Gson libary为您提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM