我正在使用 Rest Api 调用将 Pojo 转换为 XML。
下面是我的代码片段:
TestAccount.java
import javax.money.MonetaryAmount;
public class TestAccount {
private MonetaryAmount paymentAmount;
private String accountNumber;
public String getAccountNumber() {
return this.accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public MonetaryAmount getPaymentAmount() {
return this.paymentAmount;
}
public void setPaymentAmount(MonetaryAmount paymentAmount) {
this.paymentAmount = paymentAmount;
}
}
Controller.java
public class Controller extends BaseController {
@RequestMapping(value = "/javaTest", method = RequestMethod.GET, produces = { "application/xml" })
public TestAccount testMoneyPackage() {
TestAccount obj = new TestAccount();
obj.setAccountNumber("101423");
obj.setPaymentAmount(MoneyUtilityCls.of(10.898));
return obj;
}
}
在浏览器上运行网址时
<强> http://localhost:8080/api/javaTest
输出:
<OverdueAccount>
<accountNumber>101423</accountNumber>
<paymentAmount>
<currency>
<context>
<providerName>java.util.Currency</providerName>
<empty>false</empty>
</context>
<defaultFractionDigits>2</defaultFractionDigits>
<currencyCode>USD</currencyCode>
<numericCode>840</numericCode>
</currency>
<number>10.9</number>*****loss of precision*******
<negative>false</negative>
<zero>false</zero>
<precision>3</precision>
<scale>1</scale>
<positiveOrZero>true</positiveOrZero>
<positive>true</positive>
<negativeOrZero>false</negativeOrZero>
<factory>
<defaultMonetaryContext>
<precision>0</precision>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<fixedScale>false</fixedScale>
<maxScale>-1</maxScale>
<providerName/>
<empty>false</empty>
</defaultMonetaryContext>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<maxNumber/>
<minNumber/>
<maximalMonetaryContext>
<precision>0</precision>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<fixedScale>false</fixedScale>
<maxScale>-1</maxScale>
<providerName/>
<empty>false</empty>
</maximalMonetaryContext>
</factory>
<context>
<precision>0</precision>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<fixedScale>false</fixedScale>
<maxScale>-1</maxScale>
<providerName/>
<empty>false</empty>
</context>
</paymentAmount>
</OverdueAccount>
如您所见,设置时
od.setPaymentAmount(MoneyUtil.of(10.898));
我在 XML 中失去了精度
<number>10.9</number>
那些额外的 XML 标签是什么?
此问题仅出现在 MonetaryAmount 字段中,否则代码可以正常运行。 那么,将 MonetaryAmount 字段转换为 Pojo 到 XML 的正确方法是什么,反之亦然而不损失精度。
最佳答案
您能分享一下 MoneyUtil/MoneyUtilityCls 类的代码吗?
我猜测使用的 MonetaryAmount 的实现是 RoundedMoney,默认小数位数为 1,这会导致所描述的行为。
这种情况下的解决方案是让 Utility 返回另一个类(例如 Money)或更改返回的 RoundedMoney 对象的小数位数。
关于Java 9 javax.money.MonetaryAmount (JSR 354) : Unable to convert Pojo to XML and vice versa,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38393921/