Example usage for com.google.gson JsonSerializer JsonSerializer

List of usage examples for com.google.gson JsonSerializer JsonSerializer

Introduction

In this page you can find the example usage for com.google.gson JsonSerializer JsonSerializer.

Prototype

JsonSerializer

Source Link

Usage

From source file:info.raack.appliancelabeler.web.MainController.java

License:Open Source License

@RequestMapping(value = "/energy/{frequency}", method = RequestMethod.GET)
public void getEnergyData(@PathVariable("frequency") String frequency,
        @RequestParam(value = "start", required = false) Double startMillis,
        @RequestParam(value = "end", required = false) Double endMillis,
        @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // need to get latest values from stepgreen service

    EnergyMonitor energyMonitor = getCurrentEnergyMonitor(request, response);

    Date start = new Date();
    Date end = new Date();

    if (startMillis != null && endMillis != null) {
        start = new Date(startMillis.longValue());
        end = new Date(endMillis.longValue());
    } else if (startMillis != null && endMillis == null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(startMillis.longValue());
        start = new Date();
        start.setTime(startMillis.longValue());

        c.add(Calendar.DATE, 1);/*from w w w.ja v  a2  s  . c  o  m*/
        end = c.getTime();
    } else if (startMillis == null && endMillis != null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(endMillis.longValue());
        end = new Date();
        end.setTime(endMillis.longValue());

        c.add(Calendar.DATE, -1);
        start = c.getTime();

    } else {
        createOneDaySpan(energyMonitor, start, end);
    }

    if (ticks == null) {
        ticks = 300;
    }

    Date queryStart = null;
    Date queryEnd = null;

    // if the time window is less than 5 minutes, then just take the window as is; otherwise, enlarge the window to the 5 minute interval requested
    if (end.getTime() - start.getTime() > (5 * 60 * 1000)) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(start);
        queryStart = dateUtils.getPreviousFiveMinuteIncrement(cal).getTime();

        cal = new GregorianCalendar();
        cal.setTime(end);
        queryEnd = dateUtils.getNextFiveMinuteIncrement(cal).getTime();
    } else {
        queryStart = start;
        queryEnd = end;
    }

    List<SecondData> data = getEnergyDataWithLimits(energyMonitor,
            DataService.DataFrequency.valueOf(frequency.toUpperCase()), queryStart, queryEnd, ticks);
    Map<UserAppliance, List<EnergyTimestep>> predictedEnergyUsage = dataService
            .getApplianceEnergyConsumptionForMonitor(energyMonitor, algorithm.getId(), queryStart, queryEnd);
    Map<UserAppliance, List<ApplianceStateTransition>> predictedApplianceStateTransitions = dataService
            .getPredictedApplianceStateTransitionsForMonitor(energyMonitor, algorithm.getId(), queryStart,
                    queryEnd);

    JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() {
        // serialize date to milliseconds since epoch
        public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) {
            JsonArray object = new JsonArray();
            object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime()));
            object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed()));
            return object;
        }
    };

    EnergyWrapper energyWrapper = new EnergyWrapper(data, predictedEnergyUsage,
            predictedApplianceStateTransitions, database.getEnergyCost(energyMonitor));

    String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer)
            .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() {

                // skip logger
                public boolean shouldSkipClass(Class<?> clazz) {
                    return clazz.equals(Logger.class);
                }

                public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                    // skip endTime of energytimestep
                    return (fieldAttributes.getName().equals("endTime")
                            && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) ||
                    // skip userAppliance, detectionAlgorithmId of appliance state transition
                    ((fieldAttributes.getName().equals("userAppliance")
                            || fieldAttributes.getName().equals("detectionAlgorithmId"))
                            && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class);
                }
            }).create().toJson(energyWrapper);

    response.getWriter().write(dataJS);

    // set appropriate JSON response type
    response.setContentType("application/json");
}

From source file:io.bouquet.v4.GsonFactory.java

License:Apache License

/**
 * JSON constructor.//w  ww .  j a v a  2 s. c  o  m
 *
 * @param getClient() An instance of ApiClient
 */
public GsonFactory(ApiClient apiClient) {
    this.apiClient = apiClient;
    JsonDeserializer<ChosenMetric> chosenMetricDeserializer = new JsonDeserializer<ChosenMetric>() {
        @Override
        public ChosenMetric deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json.isJsonObject()) {
                JsonObject jsonObject = json.getAsJsonObject();
                Expression expression = gson.fromJson(jsonObject, Expression.class);
                return new ChosenMetric(expression);
            } else {
                return new ChosenMetric(json.getAsString());
            }
        }
    };
    JsonSerializer<ChosenMetric> chosenMetricSerializer = new JsonSerializer<ChosenMetric>() {

        @Override
        public JsonElement serialize(ChosenMetric src, Type typeOfSrc, JsonSerializationContext context) {
            if (src.getId() != null) {
                return new JsonPrimitive(src.getId());
            } else {
                return context.serialize(src.getExpression(), Expression.class);
            }
        }

    };
    JsonDeserializer<FacetMember> facetMemberDeserializer = new JsonDeserializer<FacetMember>() {
        @Override
        public FacetMember deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json.isJsonObject()) {
                JsonObject jsonObject = json.getAsJsonObject();
                if (jsonObject != null) {
                    if ("i".equals(jsonObject.get("type").getAsString())) {
                        return gson.fromJson(jsonObject, FacetMemberInterval.class);
                    } else if ("v".equals(jsonObject.get("type").getAsString())) {
                        return gson.fromJson(jsonObject, FacetMemberString.class);
                    } else {
                        // throw new ApiException("Invalid facet type");
                        return null;
                    }
                }
                // throw new ApiException("Invalid facet type");
                return null;

            } else {
                // throw new ApiException("Invalid facet type");
                return null;

            }
        }
    };
    JsonSerializer<FacetMember> facetMemberSerializer = new JsonSerializer<FacetMember>() {

        @Override
        public JsonElement serialize(FacetMember src, Type typeOfSrc, JsonSerializationContext context) {
            if (src instanceof FacetMemberInterval) {
                return context.serialize(src, FacetMemberInterval.class);
            } else if (src instanceof FacetMemberString) {
                return context.serialize(src, FacetMemberString.class);
            } else {
                return null;
            }
        }

    };

    JsonDeserializer<Credentials> credentialsDeserializer = new JsonDeserializer<Credentials>() {
        @Override
        public Credentials deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json.isJsonObject()) {
                JsonObject jsonObject = json.getAsJsonObject();
                if (jsonObject != null) {
                    if ("API".equals(jsonObject.get("type").getAsString())) {
                        return gson.fromJson(jsonObject, APICredentials.class);
                    } else if ("DBMS".equals(jsonObject.get("type").getAsString())) {
                        return gson.fromJson(jsonObject, DBMSCredentials.class);
                    } else if ("REFRESH".equals(jsonObject.get("type").getAsString())) {
                        return gson.fromJson(jsonObject, OAuth2RefreshCredentials.class);
                    } else {
                        // throw new ApiException("Invalid facet type");
                        return null;
                    }
                }
                // throw new ApiException("Invalid facet type");
                return null;

            } else {
                // throw new ApiException("Invalid facet type");
                return null;

            }
        }
    };

    JsonSerializer<Credentials> credentialsSerializer = new JsonSerializer<Credentials>() {

        @Override
        public JsonElement serialize(Credentials src, Type typeOfSrc, JsonSerializationContext context) {
            if (src instanceof APICredentials) {
                return context.serialize(src, APICredentials.class);
            } else if (src instanceof DBMSCredentials) {
                return context.serialize(src, DBMSCredentials.class);
            } else if (src instanceof OAuth2RefreshCredentials) {
                return context.serialize(src, OAuth2RefreshCredentials.class);
            } else {
                return null;
            }
        }

    };

    JsonDeserializer<Col> colSerializer = new JsonDeserializer<Col>() {
        @Override
        public Col deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json.isJsonObject()) {
                JsonObject jsonObject = json.getAsJsonObject();
                Col col = new Col();
                if (jsonObject.get("id") != null && jsonObject.get("id").isJsonNull() == false) {
                    col.setId(jsonObject.get("id").getAsString());
                }
                if (jsonObject.get("name") != null && jsonObject.get("name").isJsonNull() == false) {
                    col.setName(jsonObject.get("name").getAsString());
                }
                if (jsonObject.get("definiti") != null && jsonObject.get("definiti").isJsonNull() == false) {
                    col.setDefinition(jsonObject.get("definition").getAsString());
                }
                if (jsonObject.get("extendedType") != null
                        && jsonObject.get("extendedType").isJsonNull() == false) {
                    col.setExtendedType(gson.fromJson(jsonObject.get("extendedType"), ExtendedType.class));
                }
                if (jsonObject.get("originType") != null
                        && jsonObject.get("originType").isJsonNull() == false) {
                    col.setOriginType(OriginType.valueOf(jsonObject.get("originType").getAsString()));
                }
                if (jsonObject.get("description") != null
                        && jsonObject.get("description").isJsonNull() == false) {
                    col.setDescription(jsonObject.get("description").getAsString());
                }
                if (jsonObject.get("format") != null && jsonObject.get("format").isJsonNull() == false) {
                    col.setFormat(jsonObject.get("format").getAsString());
                }
                if (jsonObject.get("pos") != null && jsonObject.get("pos").isJsonNull() == false) {
                    col.setPos(jsonObject.get("pos").getAsInt());
                }
                if (jsonObject.get("lname") != null && jsonObject.get("lname").isJsonNull() == false) {
                    col.setLname(jsonObject.get("lname").getAsString());
                }
                if (jsonObject.get("role") != null && jsonObject.get("role").isJsonNull() == false) {
                    col.setRole(Role.valueOf(jsonObject.get("role").getAsString()));
                }
                if (col.getRole() != null && jsonObject.get("pk") != null
                        && jsonObject.get("pk").isJsonNull() == false) {
                    if (Role.DOMAIN == col.getRole()) {
                        col.setPk(gson.fromJson(jsonObject.get("pk"), DimensionPK.class));
                    } else if (Role.DATA == col.getRole()) {
                        col.setPk(gson.fromJson(jsonObject.get("pk"), MetricPK.class));
                    }
                }
                return col;

            } else {
                return null;
            }
        }
    };

    gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateAdapter(apiClient))
            .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
            .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
            .registerTypeAdapter(FacetMember.class, facetMemberDeserializer)
            .registerTypeAdapter(FacetMember.class, facetMemberSerializer)
            .registerTypeAdapter(ChosenMetric.class, chosenMetricDeserializer)
            .registerTypeAdapter(ChosenMetric.class, chosenMetricSerializer)
            .registerTypeAdapter(Credentials.class, credentialsDeserializer)
            .registerTypeAdapter(ChosenMetric.class, credentialsSerializer)
            .registerTypeAdapter(Col.class, colSerializer).create();
}

From source file:io.vertigo.vega.rest.engine.GoogleJsonEngine.java

License:Apache License

private Gson createGson() {
    return new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").setPrettyPrinting()
            //TODO  registerTypeAdapter(String.class, new EmptyStringAsNull<>())// add "" <=> null
            //.serializeNulls()//On veut voir les null
            .registerTypeAdapter(UiObject.class, new UiObjectDeserializer<>())
            .registerTypeAdapter(UiListDelta.class, new UiListDeltaDeserializer<>())
            .registerTypeAdapter(UiList.class, new UiListDeserializer<>())
            //.registerTypeAdapter(UiObjectExtended.class, new UiObjectExtendedDeserializer<>())
            /*.registerTypeAdapter(DtObjectExtended.class, new JsonSerializer<DtObjectExtended<?>>() {
               @Override/*from  w  w w.  j  a va 2  s. c o m*/
               public JsonElement serialize(final DtObjectExtended<?> src, final Type typeOfSrc, final JsonSerializationContext context) {
                  final JsonObject jsonObject = new JsonObject();
                  final JsonObject jsonInnerObject = (JsonObject) context.serialize(src.getInnerObject());
                  for (final Entry<String, JsonElement> entry : jsonInnerObject.entrySet()) {
                     jsonObject.add(entry.getKey(), entry.getValue());
                  }
                  for (final Entry<String, Serializable> entry : src.entrySet()) {
                     jsonObject.add(entry.getKey(), context.serialize(entry.getValue()));
                  }
                  return jsonObject;
               }
            })*/
            .registerTypeAdapter(FacetedQueryResult.class, new JsonSerializer<FacetedQueryResult>() {
                @Override
                public JsonElement serialize(final FacetedQueryResult facetedQueryResult, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    final JsonObject jsonObject = new JsonObject();
                    //1- add result list as data
                    final JsonArray jsonData = (JsonArray) context.serialize(facetedQueryResult.getDtList());
                    jsonObject.add("data", jsonData);

                    //2- add facet list as facets
                    final List<Facet> facets = facetedQueryResult.getFacets();
                    final JsonArray facetList = new JsonArray();
                    for (final Facet facet : facets) {
                        final JsonObject jsonFacet = new JsonObject();

                        final Map<String, Long> maps = new HashMap<>();
                        for (final Entry<FacetValue, Long> entry : facet.getFacetValues().entrySet()) {
                            maps.put(entry.getKey().getLabel().getDisplay(), entry.getValue());
                        }

                        final JsonObject jsonFacetValues = (JsonObject) context.serialize(maps);
                        final String facetName = facet.getDefinition().getLabel().getDisplay();
                        jsonFacet.add(facetName, jsonFacetValues);
                        facetList.add(jsonFacet);
                    }
                    jsonObject.add("facets", context.serialize(facetList));
                    return jsonObject;
                }
            }).registerTypeAdapter(ComponentInfo.class, new JsonSerializer<ComponentInfo>() {
                @Override
                public JsonElement serialize(final ComponentInfo componentInfo, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    final JsonObject jsonObject = new JsonObject();
                    jsonObject.add(componentInfo.getTitle(), context.serialize(componentInfo.getValue()));
                    return jsonObject;
                }
            }).registerTypeAdapter(List.class, new JsonSerializer<List>() {

                @Override
                public JsonElement serialize(final List src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    if (src.isEmpty()) {
                        return null;
                    }
                    return context.serialize(src);
                }
            }).registerTypeAdapter(Map.class, new JsonSerializer<Map>() {

                @Override
                public JsonElement serialize(final Map src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    if (src.isEmpty()) {
                        return null;
                    }
                    return context.serialize(src);
                }
            }).registerTypeAdapter(DefinitionReference.class, new JsonSerializer<DefinitionReference>() {

                @Override
                public JsonElement serialize(final DefinitionReference src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    return context.serialize(src.get().getName());
                }
            }).registerTypeAdapter(Option.class, new JsonSerializer<Option>() {

                @Override
                public JsonElement serialize(final Option src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    if (src.isDefined()) {
                        return context.serialize(src.get());
                    }
                    return null; //rien
                }
            }).registerTypeAdapter(Class.class, new JsonSerializer<Class>() {

                @Override
                public JsonElement serialize(final Class src, final Type typeOfSrc,
                        final JsonSerializationContext context) {
                    return new JsonPrimitive(src.getName());
                }
            }).addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(final FieldAttributes arg0) {
                    if (arg0.getAnnotation(JsonExclude.class) != null) {
                        return true;
                    }
                    return false;
                }

                @Override
                public boolean shouldSkipClass(final Class<?> arg0) {
                    return false;
                }
            }).create();
}

From source file:me.figo.internal.GsonAdapter.java

License:Open Source License

public static Gson createGson() {
    JsonSerializer<Date> serializer = new JsonSerializer<Date>() {
        @Override/*from  ww  w .java 2 s .co  m*/
        public JsonElement serialize(Date src, Type type, JsonSerializationContext context) {
            if (src == null)
                return null;

            String formatted = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(src);
            return new JsonPrimitive(formatted.substring(0, 22) + ":" + formatted.substring(22));
        }
    };

    JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            if (json == null)
                return null;

            String s = json.getAsString().replace("Z", "+0000");
            try {
                return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ").parse(s);
            } catch (ParseException e) {
                return null;
            }
        }
    };

    return new GsonBuilder().registerTypeAdapter(Date.class, serializer)
            .registerTypeAdapter(Date.class, deserializer).excludeFieldsWithoutExposeAnnotation().create();
}

From source file:net.bhira.sample.common.JsonUtil.java

License:Open Source License

/**
 * Create a customized version of Gson that handles Date formats and timezones correctly. It
 * uses UTC date format for parsing and formating dates and expects the date string values to be
 * formatted in UTC timezone.// w w  w  . j  a  v a 2 s  .c om
 *
 * @return an instance of {@link com.google.gson.Gson}.
 */
public static Gson createGson() {

    // create a custom serializer for dates
    JsonSerializer<Date> serializer = new JsonSerializer<Date>() {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
            formatter.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
            return new JsonPrimitive(formatter.format(src));
        }
    };

    // create a custom de-serializer for dates
    JsonDeserializer<Date> deserializer = new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json == null) {
                return null;
            }
            String date = json.getAsString();
            SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
            formatter.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
            try {
                return formatter.parse(date);
            } catch (ParseException e) {
                throw new JsonParseException("Error parsing date " + date, e);
            }

        }
    };

    // create a custom gson that uses the custom date serializer/deserializer
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, serializer);
    gsonBuilder.registerTypeAdapter(Date.class, deserializer);
    return gsonBuilder.create();
}

From source file:net.servicestack.client.JsonSerializers.java

License:Open Source License

public static JsonSerializer<Date> getDateSerializer() {
    return new JsonSerializer<Date>() {
        @Override/*from   ww w  .  jav  a 2s . c  om*/
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return src == null ? null : new JsonPrimitive(Utils.toJsonDate(src));
        }
    };
}

From source file:net.servicestack.client.JsonSerializers.java

License:Open Source License

public static JsonSerializer<TimeSpan> getTimeSpanSerializer() {
    return new JsonSerializer<TimeSpan>() {
        @Override/*from  ww w .j  av  a 2  s. c  o  m*/
        public JsonElement serialize(TimeSpan src, Type typeOfSrc, JsonSerializationContext context) {
            return src == null ? null : new JsonPrimitive(src.toXsdDuration());
        }
    };
}

From source file:net.servicestack.client.JsonSerializers.java

License:Open Source License

public static JsonSerializer<UUID> getGuidSerializer() {
    return new JsonSerializer<UUID>() {
        @Override/*from  ww  w.  ja  v  a  2  s.com*/
        public JsonElement serialize(UUID src, Type typeOfSrc, JsonSerializationContext context) {
            return src == null ? null : new JsonPrimitive(Utils.toGuidString(src));
        }
    };
}

From source file:org.lightcouch.CouchDbClientBase.java

License:Apache License

/**
 * Builds {@link Gson} and registers any required serializer/deserializer.
 * @return {@link Gson} instance/*  w  w  w.j  a v a  2  s.c o  m*/
 */
private Gson initGson(GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
        public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return json.getAsJsonObject();
        }
    });

    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonSerializer<JsonObject>() {
        @Override
        public JsonElement serialize(JsonObject jsonObject, Type type,
                JsonSerializationContext jsonSerializationContext) {
            return jsonObject;
        }
    });
    return gsonBuilder.create();
}

From source file:org.mitre.oauth2.view.TokenIntrospection.java

License:Apache License

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        @Override// w ww.  ja  va 2  s.  com
        public boolean shouldSkipField(FieldAttributes f) {
            /*
            if (f.getDeclaringClass().isAssignableFrom(OAuth2AccessTokenEntity.class)) {
               // we don't want to serialize the whole object, just the scope and timeout
               if (f.getName().equals("scope")) {
                  return false;
               } else if (f.getName().equals("expiration")) {
                  return false;
               } else {
                  // skip everything else on this class
                  return true;
               }
            } else {
               // serialize other classes without filter (lists and sets and things)
               return false;
            }
            */
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            } else {
                return false;
            }
        }

    }).registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() {
        public JsonElement serialize(OAuth2AccessTokenEntity src, Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject token = new JsonObject();

            token.addProperty("valid", true);

            JsonArray scopes = new JsonArray();
            for (String scope : src.getScope()) {
                scopes.add(new JsonPrimitive(scope));
            }
            token.add("scope", scopes);

            token.add("expires", context.serialize(src.getExpiration()));

            return token;
        }

    }).setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();

    response.setContentType("application/json");

    Writer out = response.getWriter();

    Object obj = model.get("entity");
    if (obj == null) {
        obj = model;
    }

    gson.toJson(obj, out);

}