Set POJO for Gson when JSON key has a dash

﹥>﹥吖頭↗ 提交于 2020-02-01 04:07:05

问题


The JSON string is:

{
    "translation": ["some words"],
    "basic": {
        "us-phonetic": "'flæbɚɡæstɪd",
        "phonetic": "'flæbɚɡæstɪd",
        "uk-phonetic": "'flæbəga:stid",
        "explains": ["v. some words",
            "adj. some words"
        ]
    }
}

But Java can not have a value with a "-" in it. So how to get "us-phonetic"?


回答1:


Create a POJO class to represent your JSON and decorate your fields with the SerializedName annotation.

gson uses @SerializedName("json_name") when the name of the JSON field and the name of the java field are different.

I have taken the liberty to simplify your JSON for example purposes:

{
  "us-phonetic": "'flæbɚɡæstɪd",
  "phonetic": "'flæbɚɡæstɪd",
  "uk-phonetic": "'flæbəga:stid"
}

Use the following class to deserialize your JSON:

public class Basic {
  @SerializedName("us-phonetic")
  private String usPhonetic;

  @SerializedName("phonetic")
  private String phonetic;

  @SerializedName("uk-phonetic")
  private String ukPhonetic;
}

To deserialize:

Basic b = gson.fromJson(json, Basic.class);


来源:https://stackoverflow.com/questions/37729066/set-pojo-for-gson-when-json-key-has-a-dash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!