I'm using Gson to extraxt some fields. By the way I don't want to create a class due to the fact that I need only one value in all JSON response. Here's my response:
{
"result": {
"name1": "value1",
"name2": "value2",
},
"wantedName": "wantedValue"
}
I need wantedValue
but I don't want to create the entire class for deserialization. Is it possible to achieve this using Gson?
If you need one field only, use JSONObject
.
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws JSONException {
String str = "{" +
" \"result\": {" +
" \"name1\": \"value1\"," +
" \"name2\": \"value2\"," +
" }," +
" \"wantedName\": \"wantedValue\"" +
"}";
JSONObject jsonObject = new JSONObject(str);
System.out.println(jsonObject.getString("wantedName"));
}
Output:
wantedValue