gson 在Android上将JSON的特定子字段Map到Java Class属性

zqdjd7g9  于 11个月前  发布在  Android
关注(0)|答案(1)|浏览(133)

我有一个这样的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
  },

...
]

字符串
这是我从here获取的国家列表。我将JSONMap到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”将被解析为对象,因为它们内部有其他参数,对吗?例如,是否可以将JSON中“flags”字段内的“png”字段直接Map到我的类参数“bandeira”?
我试过把@SerializedName符号改成像@SerializedName("flags.png")这样的符号,但是不起作用。我想有一种特殊的方法可以做到这一点。

c9x0cxw0

c9x0cxw01#

一种解决方案是在转换为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}]

相关问题