2

I have the following JSON:

{
   "LightObjectSet": {
      "Objects": {
         "Org": {
            "State": "Unchanged",
            "Guid": "00000000-0000-0000-0000-000000000000",
            "Id": "39",
            "Name": "Test org",
            "ShortName": "Test"
         }
      }
   }
}

Can I deserialize only Org object (not all structure) using Gson?

1

1 Answer 1

0

Try this. Just a note, the deserialized Org class is not following Java naming conventions to match the JSON. If you want to follow them, you need to annotate fields with @SerializedName

public class Q13363304 {

    class Org {

        String State;
        String Guid;
        int Id;
        String Name;
        String ShortName;

        @Override
        public String toString() {
            return "Org [State=" + State + ", Guid=" + Guid + ", Id=" + Id
                    + ", Name=" + Name + ", ShortName=" + ShortName + "]";
        }

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String json = "{ \"LightObjectSet\": { \"Objects\": { \"Org\": { \"State\":\"Unchanged\", \"Guid\":\"00000000-0000-0000-0000-000000000000\", \"Id\":\"39\", \"Name\":\"Test org\", \"ShortName\":\"Test\" } } } }";

        JsonObject root = new JsonParser().parse(json).getAsJsonObject();
        JsonObject lightObjectSet = root.get("LightObjectSet").getAsJsonObject();
        JsonObject objects = lightObjectSet.get("Objects").getAsJsonObject();
        JsonElement org = objects.get("Org");

        Gson g = new Gson();

        Org o = g.fromJson(org, Org.class);
        System.out.print(o);

    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.