1 回答
TA贡献1833条经验 获得超4个赞
我修改了你的代码,试试下面的代码。基本上,我做了以下几件事。
Order 内部没有 Chargeback 对象的 getter 和 setter,所以添加了。
注释掉 @JsonIgnore 注释。
课程如下
class Chargeback {
private double amount;
private String currency;
// Getter Methods
// @JsonIgnore
public double getAmount() {
return amount;
}
// @JsonInclude(Include.NON_NULL)
public String getCurrency() {
return currency;
}
// Setter Methods
public void setAmount(double cb_amount) {
this.amount = cb_amount;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
public class Order {
private double amount;
Chargeback ChargebackObject;
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public Chargeback getChargebackObject() {
return ChargebackObject;
}
public void setChargebackObject(Chargeback chargebackObject) {
ChargebackObject = chargebackObject;
}
}
下面给出了用于测试生成 Json 的代码。
public class Test1 {
public static void main(String[] args) throws Exception {
Chargeback chargeback = new Chargeback();
chargeback.setAmount(1234.00);
chargeback.setCurrency("BHD");
Order order = new Order();
order.setAmount(2345.00);
order.setChargebackObject(chargeback);
ObjectMapper mapper = new ObjectMapper();
String toJson = null;
try {
toJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(order);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Complete Json = " + toJson);
// From Json String to Java Object
ObjectMapper mapper1 = new ObjectMapper();
Order order1 = mapper.readValue(toJson, Order.class);
System.out.println("Order Object -> " + order1);
}
}
下面给出生成json。
{
"amount" : 2345.0,
"chargebackObject" : {
"amount" : 1234.0,
"currency" : "BHD"
}
}
添加回答
举报