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"
?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With