我有一个像这样的 JSON:
[
{
"flags": {
"png": "https://flagcdn.com/w320/cx.png",
"svg": "https://flagcdn.com/cx.svg",
"alt": ""
},
"name": {
"common": "Christmas Island",
"official": "Territory of Christmas Island",
"nativeName": {
"eng": {
"official": "Territory of Christmas Island",
"common": "Christmas Island"
}
}
},
"region": "Oceania",
"population": 2072
},
...
]
这是我从这里获取的国家/地区列表。我将该 JSON 映射到 Java 类,如下所示:
public class Pais {
@SerializedName("name")
@Expose
private String nome;
@SerializedName("region")
@Expose
private String regiao;
@SerializedName("population")
@Expose
private int populacao;
@SerializedName("flags")
@Expose
private String bandeira;
}
然后我使用 GSON 来序列化整个事情
executor.execute(() -> {
Conexao conexao = new Conexao();
String URL = "https://restcountries.com/v2/all?fields=name,region,population,flag,numericCode";
InputStream inputStream = conexao.obterRespostaHTTP(URL);
Auxiliador auxiliador = new Auxiliador();
String textoJSON = auxiliador.converter(inputStream);
Gson gson = new Gson();
if (textoJSON != null) {
Type type = new TypeToken<ArrayList<Pais>>() {
}.getType();
paises = gson.fromJson(textoJSON, type);
handler.post(() -> {
paisAdapter = new PaisAdapter(this, paises);
listView.setAdapter(paisAdapter);
});
}
});
但问题是,字段“name”和“flags”将被解析为对象,因为它们内部还有其他参数,对吧?例如,是否可以执行类似将“flags”字段内的“png”字段从 JSON 直接映射到我的类参数“bandeira”的操作?
我尝试将
@SerializedName
符号更改为 @SerializedName("flags.png")
之类的内容,但没有成功。我想有一种特定的方法可以做到这一点。
一种解决方案是在转换为 POJO 之前转换 JSON 结构。您可以尝试 JSON 库 Josson,它使用 Jackson 而不是 Gson。
public class Pais {
private String nome;
private String regiao;
private int populacao;
private String bandeira;
}
https://github.com/octomix/josson
ArrayList<Pais> paises = Josson.fromJsonString(textoJSON)
.getJosson(
"map(nome: name.common," +
" regiao: region," +
" populacao: population," +
" bandeira: flags.png)")
.convertValue();
System.out.println(paises);
输出
[{nome=Christmas Island, regiao=Oceania, populacao=2072, bandeira=https://flagcdn.com/w320/cx.png}]