vancake vancake - 1 year ago 95
JSON Question

Set POJO for Gson when JSON key has a dash

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

Answer Source

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 {
  private String usPhonetic;

  private String phonetic;

  private String ukPhonetic;

To deserialize:

Basic b = gson.fromJson(json, Basic.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download