-1

im trying to read the following json in java.

{
"guiCarport": {
    "width": 500,
    "depth": 500,
    "height": 230
},
"guiRoof": {
    "gableRoof": false,
    "overhang": {
        "sides": 20,
        "front": 20,
        "back": 20
    }
},
"guiShed": {
    "shed": false,
    "depth": 300,
    "doorPlacement": 0,
    "side": "Foran",
    "rotateDoor": false
}
}

so far my java code looks like this, in a java servlet:

    String json = (String) request.getParameter("json");

    Gson gson = new Gson();
    JsonObject obj = gson.fromJson(json, JsonObject.class);

    JsonElement base = obj.get("guiCarport");
    JsonElement roof = obj.get("guiRoof");
    JsonElement shed = obj.get("guiShed");

What is the easiest way for me to read the values of the objects and assign them to variables? I Have custom classes created for the different object, but i need a way to get the values first. Thanks!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Why can't you just convert it to your custom class immediately instead of converting to `JsonObject`? – Shadov May 01 '17 at 15:24
  • How would i go about and do that? – KasperOnFire May 01 '17 at 15:27
  • 1
    Put your json on this site http://www.jsonschema2pojo.org, pick `Gson` and click zip, it's gonna generate java classes from your json. Then just use `gson.fromJson(json, Example.class)` (or something else if you wanna rename generated `Example.java`) and your json is gonna be converted to those objects. – Shadov May 01 '17 at 15:47

2 Answers2

-1

You can convert json data into a HashMap first . This way you will get the values

  Type type = new TypeToken<Map<String, String>>(){}.getType();
  Map<String, String> myMap = gson.fromJson(jsonData, type);
Vikrant
  • 178
  • 4
-1

If you have custom classes for "guiCarport", "guiRoof" and "guiShed". Then please make a data holder like the one below

class ResponseHolder {
    private GuiCarportType guiCarport;
    private GuiRoofType guiRoof;
    private GuiShedType guiShed;

    //Getters and setters
}

Now you can pasre the response direclty into the object as

ResponseHolder holder = gson.fromJson(jsonData, ResponseHolder.class);

Then you can get individual objects and in turn their values with getters.

Master Po
  • 1,497
  • 1
  • 23
  • 42