7

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 Answer 1

24

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);
3
  • But still not working.don't know why...just get a null
    – vancake
    Commented Jun 9, 2016 at 15:59
  • Very strange as I have just tested the above code and it works. Where do you get a null ? Commented Jun 9, 2016 at 16:22
  • OK,I know what's wrong.I naming usphonetic instead of usPhonetic
    – vancake
    Commented Jun 10, 2016 at 2:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.