Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "us-phonetic"?

like image 384
vancake Avatar asked Jun 09 '16 14:06

vancake


People also ask

How do I change from JSON to pojo?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

How do I read a JSON file in GSON?

Reading and writing JSON using GSON is very easy. You can use these two methods: toJSON() : It will convert simple pojo object to JSON string. FromJSON() : It will convert JSON string to pojo object.

Is GSON and JSON are same?

Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google. Standardized − Gson is a standardized library that is managed by Google.


1 Answers

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);
like image 80
Clive Seebregts Avatar answered Sep 28 '22 00:09

Clive Seebregts