4

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?

Angelo
  • 867
  • 3
  • 15
  • 33
  • You can probably parse the JSON yourself to find the "wantedName" value. – Cruncher Oct 23 '13 at 18:17
  • @Cruncher I was thinking about regex but I would like to avoid using it if possible. – Angelo Oct 23 '13 at 18:18
  • you may create a `ExclusionStrategy`, see here : http://stackoverflow.com/questions/4802887/gson-how-to-exclude-specific-fields-from-serialization-without-annotations – Amar Oct 23 '13 at 18:19

3 Answers3

5

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
Maxim Shoustin
  • 78,004
  • 28
  • 199
  • 222
1

If you don't have to use Gson, I would use https://github.com/douglascrockford/JSON-java. You can easily extract single fields. I could not find a way to do something this simple using Gson.

You would just do

String wantedName = new JSONObject(jsonString).getString("wantedName");
Alper Akture
  • 2,375
  • 1
  • 29
  • 43
0

Can use just a portion of gson, using it just to parse the json:

Reader reader = /* create reader from source */
Streams.parse(new JsonReader(reader)).getAsJsonObject().get("wantedValue").getAsString();
Chris Lohfink
  • 15,852
  • 1
  • 28
  • 38