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
  • 907
  • 3
  • 16
  • 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

4 Answers4

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
  • 77,483
  • 27
  • 203
  • 225
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,445
  • 1
  • 30
  • 44
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
  • 16,150
  • 1
  • 29
  • 38
0

Here is a version which will work with gson version 2.10

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class Main {
    public static void main(String[] args) {

        String str = "{" +
                "    \"result\": {" +
                "        \"name1\": \"value1\"," +
                "        \"name2\": \"value2\"" +
                "    }," +
                "    \"wantedName\": \"wantedValue\"" +
                "}";

        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(str, JsonObject.class);

        System.out.println(jsonObject.get("wantedName").getAsString());
    }
}
Nico
  • 111
  • 10