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

4
我有一个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;
    }
}

这是我设置值的方法:
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.

可以有人帮我怎么做这个吗?
最好的问候

1
这个问题中的答案对您有用吗?https://dev59.com/FWsz5IYBdhLWcg3w9s2r - Jaime Garcia
2个回答

7

XStream或者GSON,就像其他答案中提到的一样,可以帮助你实现排序。按照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));     

使用GSON,您的代码将会像这样

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

选择你的库并开始使用。

非常感谢hd1,我尝试了你上面给出的两个答案,但仍然遇到相同的异常 :( - Java Questions

1
你可以使用Gson库来帮助你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接