2013-04-14 35 views
3

我哈瓦一个POJO为我设置的值,该POJO是:如何将Java POJO转换为JSON字符串?

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

这个问题的答案是否适合你? http://stackoverflow.com/questions/7539954/java-json-serialization-best-practice –

回答

6

XStreamGSON,如其他答复中提到,将整理您。按照JSON tutorial on XStream和您的代码将是这个样子:

 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,你的代码将look like this

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

选择你的图书馆去。

+0

非常感谢hd1,试着用上面给出的答案,但仍然得到相同的异常:( –

1

可以使用GSON libary做赞成你