我正在使用Rest Api调用将Pojo转换为XML。Java 9 javax.money.MonetaryAmount(JSR 354):无法将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,反之亦然,而不会损失精度。
“在这种情况下,解决方案将使实用程序返回另一个类(例如Money)或更改返回的RoundedMoney对象的小数位数。”有效。谢谢。 – AftabLib