Leopik
Leopik

Reputation: 333

getting exact part of json

I have a json string, here is example

{
   "Param1":"Value1",
   "Param2":{...}
   "ParamThatINeed":{...}
}

I want to get only "ParamThatINeed" object using gson lib in java, what is the best way to get what I need - write root class, then write class for "ParamThatINeed" and then decode json and use only "ParamThatINeed" object?

Or maybe it's better to beforehand convert my jsonString to another string, which will be only "ParamThatINeed" jsonString object using for example regexp? Or maybe there is a better way?

Upvotes: 1

Views: 67

Answers (2)

dimo414
dimo414

Reputation: 48794

Your suggested solution is painless and extensible (i.e. if you decide to read an additional field in the future, you just add another field to your object). In general that's exactly how you want to use Gson - construct the necessary Java classes to represent the data you care about and Gson will silently discard the fields you don't care about. For your example that could look like:

private static final Gson GSON = ...;

public static class MyJsonData {
  private final ParamThatINeed paramThatINeed;

  public ParamThatINeed getParamThatINeed() { ... }
}

public static class ParamThatINeed {
  ...
}

public static ParamThatINeed extractParamThatINeed(String json) {
  return GSON.fromJson(json, MyJsonData.class).getParamThatINeed();
}

You could parse the field yourself as @GuiSim suggests, but this won't scale as easily if your requirements change, and generally speaking the idea behind Gson is to avoid working directly with JsonElement and related classes.

I would definitely discourage a pre-processing step converting the JSON string into a different format. Structured data and string manipulations don't mix, as they lead to brittle code. JSON parsing libraries like Gson exist exactly to avoid such string manipulations.

Upvotes: 1

GuiSim
GuiSim

Reputation: 7559

JsonObject jobj = new Gson().fromJson(YOUR_JSON_HERE, JsonObject.class);
JsonElement value = jobj.get("ParamThatINeed");

value will contain the element associated with the ParamThatINeed key.

Upvotes: 1

Related Questions