Gson deserialize json with varying value types

后端 未结 2 1332
长情又很酷
长情又很酷 2020-12-10 07:43

I\'m trying to deserialize a JSONArray with Gson, one the values\' type can vary, the value \"in_wanted\" can be either a boolean or a JSONOb

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 08:14

    You could do a manual parsing, something like:

    JsonParser parser = new JsonParser();
    JsonObject rootObject = parser.parse(yourJsonString).getAsJsonObject();
    JsonObject movieObject = rootObject
                               .getAsJsonArray("movies")
                               .get(0).getAsJsonObject();
    JsonElement inWantedElement = movieObject.get("in_wanted");
    
    //Check if "in_wanted" element is a boolean or an object
    if (inWantedElement.isJsonObject()) {
        //Process the element as an object...
        //for example get the element "value"...
        boolean value = inWantedElement
                          .getAsJsonObject()
                          .getAsJsonObject("profile")
                          .getAsJsonPrimitive("value")
                          .getAsBoolean();
    }
    else if (inWantedElement.isJsonPrimitive()) {
        //Process the element as a boolean...
        boolean inWanted = inWantedElement.getAsBoolean();
    }
    

    Note: see Gson API documentation for further info about types JsonObject, JsonArray, JsonElement, and so on...

提交回复
热议问题