我想反序列化以下JSON(原始Exchange
值中包含约100 s的动态值):
{
"Exchange1": {
"EUR": [
"CNY",
"USD"
],
"INR": [
"USD",
"CNY"
]
},
"Exchange2": {
"BRL": [
"EUR",
"USD",
"INR"
],
"JPY": [
"USD",
"EUR",
"CNY"
]
},
....
}
我正在使用http://www.jsonschema2pojo.org/,但是它正在生成一个带文字值(“ Exchange1”,“ EUR”等)的Java类,而无论动态String值是多少,我都需要对其进行迭代:
如何用Java描述此JSON?
You cannot have POJOs here (in sane sense), but people tend to use POJO-generators that do not do ahead analysis even for dynamic objects. "Dynamic" objects should be typically mapped using java.util.Map
(ordered implementation) + unique values can be mapped using java.util.Set
(ordered implementation). Thus, if you have a custom enumeration for the currencies, say something like
enum Currency {
BRL,
CNY,
EUR,
INR,
JPY,
USD,
}
then you can easily define the mapping without any POJOs that do not look applicable here at all:
private static final Type exchangesType = new TypeToken<Map<String, Map<Currency, Set<Currency>>>>() {
}.getType();
final Map<String, Map<Currency, Set<Currency>>> exchanges = gson.fromJson(jsonReader, exchangesType);
System.out.println(exchanges);
So the trivial toString()
output will be as follows:
{Exchange1={EUR=[CNY, USD], INR=[USD, CNY]}, Exchange2={BRL=[EUR, USD, INR], JPY=[USD, EUR, CNY]}}
如果您不喜欢Currency
枚举的想法(必须始终使用最新的枚举进行更新,等等),那么您可以简单地将货币标记声明为java.lang.String
并获得相同的结果:
private static final Type exchangesType = new TypeToken<Map<String, Map<String, Set<String>>>>() {
}.getType();
final Map<String, Map<String, Set<String>>> exchanges = gson.fromJson(jsonReader, exchangesType);
System.out.println(exchanges);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句