2

Given the following JSON response:

{
    "status": "OK",
    "regions": [
        {
            "id": "69",
            "name": "North Carolina Coast",
            "color": "#01162c",
            "hasResorts": 1
        },
        {
            "id": "242",
            "name": "North Carolina Inland",
            "color": "#01162c",
            "hasResorts": 0
        },
        {
            "id": "17",
            "name": "North Carolina Mountains",
            "color": "#01162c",
            "hasResorts": 1
        },
        {
            "id": "126",
            "name": "Outer Banks",
            "color": "#01162c",
            "hasResorts": 1
        }
    ]
}

I'm trying to create a List of Region objects. Here's a very abridged version of my current code:

JSONObject jsonObject = new JSONObject(response);
String regionsString = jsonObject.getString("regions");                             
Type listType = new TypeToken<ArrayList<Region>>() {}.getType();                                
List<Region> regions = new Gson().fromJson(regionsString, listType);  

This is all working fine. However, I'd like to exclude the regions in the final List that hasResorts == 0. I realize I can loop through the actual JSONObjects and check them before calling fromJSON on each region. But I'm assuming there is a GSON specific way of doing this.

I was looking at the ExclusionStrategy(). Is there a simple way to implement this to JSON deserialization?

SBerg413
  • 14,515
  • 6
  • 62
  • 88

1 Answers1

2

ExclusionStrategy won't help you since it works without the context of deserialization. Indeed, you can exclude only a specific kind of class. I think that best way of doing it is through custom deserialization. Here is what I mean (you can copy&paste&try immediately):

package stackoverflow.questions.q19912055;

import java.lang.reflect.Type;
import java.util.*;

import stackoverflow.questions.q17853533.*;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

public class Q19912055 {

    class Region {
        String id;
        String name;
        String color;
        Integer hasResorts;
        @Override
        public String toString() {
            return "Region [id=" + id + ", name=" + name + ", color=" + color
                    + ", hasResorts=" + hasResorts + "]";
        }


    }

    static class RegionDeserializer implements JsonDeserializer<List<Region>> {
        public List<Region> deserialize(JsonElement json, Type typeOfT,
                JsonDeserializationContext context) throws JsonParseException {

            if (json == null)
                return null;
            ArrayList<Region> al = new ArrayList<Region>();
            for (JsonElement e : json.getAsJsonArray()) {

                boolean deserialize = e.getAsJsonObject().get("hasResorts")
                        .getAsInt() > 0;
                if (deserialize)
                    al.add((Region) context.deserialize(e, Region.class));
            }

            return al;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String json = 
            "  [                                   "+
            "        {                                            "+
            "            \"id\": \"69\",                          "+
            "            \"name\": \"North Carolina Coast\",      "+
            "            \"color\": \"#01162c\",                  "+
            "            \"hasResorts\": 1                        "+
            "        },                                           "+
            "        {                                            "+
            "            \"id\": \"242\",                         "+
            "            \"name\": \"North Carolina Inland\",     "+
            "            \"color\": \"#01162c\",                  "+
            "            \"hasResorts\": 0                        "+
            "        },                                           "+
            "        {                                            "+
            "            \"id\": \"17\",                          "+
            "            \"name\": \"North Carolina Mountains\",  "+
            "            \"color\": \"#01162c\",                  "+
            "            \"hasResorts\": 1                        "+
            "        },                                           "+
            "        {                                            "+
            "            \"id\": \"126\",                         "+
            "            \"name\": \"Outer Banks\",               "+
            "            \"color\": \"#01162c\",                  "+
            "            \"hasResorts\": 1                        "+
            "        }                                            "+
            "    ]                                                ";




        Type listType = new TypeToken<ArrayList<Region>>() {}.getType();                                
        List<Region> allRegions = new Gson().fromJson(json, listType); 
        System.out.println(allRegions);

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(listType, new RegionDeserializer());
        Gson gson2 = builder.create();

        List<Region> regionsHaveResort = gson2.fromJson(json, listType); 
        System.out.println(regionsHaveResort);

    }

}
giampaolo
  • 6,906
  • 5
  • 45
  • 73