Angelo
Angelo

Reputation: 937

How to deserialize only some fields in JSON?

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?

Upvotes: 4

Views: 3531

Answers (4)

Nico
Nico

Reputation: 129

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());
    }
}

Upvotes: 0

Alper Akture
Alper Akture

Reputation: 2465

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");

Upvotes: 1

Chris Lohfink
Chris Lohfink

Reputation: 16400

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();

Upvotes: 0

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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

Upvotes: 5

Related Questions