Example usage for com.google.gson JsonSerializationContext serialize

List of usage examples for com.google.gson JsonSerializationContext serialize

Introduction

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

Prototype

public JsonElement serialize(Object src);

Source Link

Document

Invokes default serialization on the specified object.

Usage

From source file:org.mule.modules.handshake.client.serialization.AbstractHandshakeSerializer.java

License:CPAL v1.0

@Override
public JsonElement serialize(final T src, final Type typeOfSrc, final JsonSerializationContext context) {
    try {//  ww  w.  ja v a  2s  . co m
        @SuppressWarnings("unchecked")
        final Map<String, Object> mappedObject = BeanUtils.describe(src);
        mappedObject.remove("class");
        updateMapWithNestedObjects(mappedObject, src);
        return context.serialize(mappedObject);
    } catch (final HandshakeAPIException e) {
        throw e;
    } catch (final Exception e) {
        throw new RuntimeException("This won't happen, rigth?", e);
    }
}

From source file:org.n52.matlab.connector.json.MatlabExceptionSerializer.java

License:Open Source License

@Override
public JsonElement serialize(MatlabException e, Type type, JsonSerializationContext ctx) {
    JsonObject object = new JsonObject();
    object.add(MatlabJSONConstants.ID, ctx.serialize(e.getId()));
    object.add(MatlabJSONConstants.EXCEPTION, ctx.serialize(e.getMessage()));
    return object;
}

From source file:org.ohmage.dagger.OhmageModule.java

License:Apache License

@Provides
@Singleton//from w ww .  j  av a  2 s . c  o  m
Gson provideGson() {
    GsonBuilder gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory())
            .registerTypeAdapter(Prompt.class, new BasePrompt.PromptDeserializer())
            .registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if ((src == Math.floor(src)) && !Double.isInfinite(src)) {
                        return context.serialize(src.intValue());
                    }

                    return context.serialize(src);
                }
            });
    TriggerInit.injectDeserializers(gson);
    return gson.create();
}

From source file:org.openhab.io.imperihome.internal.io.DeviceParametersSerializer.java

License:Open Source License

@Override
public JsonElement serialize(DeviceParameters params, Type type,
        JsonSerializationContext jsonSerializationContext) {
    JsonArray result = new JsonArray();
    for (DeviceParam param : params.values()) {
        result.add(jsonSerializationContext.serialize(param));
    }/*from  w  w w.  j  a  va  2 s.  c  o  m*/
    return result;
}

From source file:org.openhab.io.neeo.internal.serialization.NeeoBrainDeviceSerializer.java

License:Open Source License

@Override
public JsonElement serialize(NeeoDevice device, @Nullable Type deviceType,
        @Nullable JsonSerializationContext jsonContext) {
    Objects.requireNonNull(device, "device cannot be null");
    Objects.requireNonNull(deviceType, "deviceType cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    final JsonObject jsonObject = new JsonObject();

    final String adapterName = device.getUid().getNeeoUID();
    // jsonObject.addProperty("apiversion", "1.0"); // haven't decided if needed
    jsonObject.addProperty("adapterName", adapterName);
    jsonObject.addProperty("driverVersion", device.getDriverVersion());

    jsonObject.addProperty("type", device.getType().toString());
    jsonObject.addProperty("manufacturer", device.getManufacturer());
    jsonObject.addProperty("name", device.getName());
    jsonObject.addProperty("tokens", "");

    final NeeoDeviceTiming timing = device.getDeviceTiming();
    if (timing != null) {
        final JsonObject timingObj = new JsonObject();
        timingObj.addProperty("standbyCommandDelay", timing.getStandbyCommandDelay());
        timingObj.addProperty("sourceSwitchDelay", timing.getSourceSwitchDelay());
        timingObj.addProperty("shutdownDelay", timing.getShutdownDelay());
        jsonObject.add("timing", timingObj);
    }//w  ww .  j ava  2 s . c  om

    /**
     * Setup only really good for SDK discovery (which we don't do)
     * 'setup': { 'discovery': true,'registration': false,'introheader': 'header text','introtext': 'some hints'}
     */
    jsonObject.add("setup", new JsonObject());

    jsonObject.add("deviceCapabilities", jsonContext.serialize(device.getDeviceCapabilities()));

    final JsonObject deviceObj = new JsonObject();
    final String deviceName = device.getName();
    deviceObj.addProperty("name", deviceName);
    deviceObj.add("tokens", new JsonArray());
    jsonObject.add("device", deviceObj);

    final String specificName = device.getSpecificName();
    if (specificName != null && StringUtils.isNotEmpty(specificName)) {
        deviceObj.addProperty("specificname", specificName);
        jsonObject.addProperty("specificname", specificName);
    } else if (StringUtils.isNotEmpty(deviceName)) {
        deviceObj.addProperty("specificname", deviceName);
        jsonObject.addProperty("specificname", deviceName);
    }

    final String iconName = device.getIconName();
    if (iconName != null && StringUtils.isNotEmpty(iconName)) {
        deviceObj.addProperty("icon", iconName);
        jsonObject.addProperty("icon", iconName);
    }

    final List<JsonObject> capabilities = new ArrayList<>();
    for (NeeoDeviceChannel channel : device.getExposedChannels()) {
        final NeeoCapabilityType capabilityType = channel.getType();

        final String compPath = NeeoConstants.CAPABILITY_PATH_PREFIX + "/" + adapterName + "/"
                + channel.getItemName() + "/" + channel.getSubType() + "/" + channel.getChannelNbr();

        final String uniqueItemName = channel.getUniqueItemName();
        final String sensorItemName = uniqueItemName
                + (StringUtils.endsWithIgnoreCase(uniqueItemName, NeeoConstants.NEEO_SENSOR_SUFFIX) ? ""
                        : NeeoConstants.NEEO_SENSOR_SUFFIX);

        if (capabilityType == NeeoCapabilityType.BUTTON) {
            final String name = StringUtils.isEmpty(channel.getLabel()) ? uniqueItemName : channel.getLabel();

            if (channel.getKind() == NeeoDeviceChannelKind.TRIGGER) {
                final String path = compPath + "/button/trigger";
                capabilities.add(createBase(name, channel.getLabel(), capabilityType.toString(), path));
            } else {
                final String value = channel.getValue();
                final String path = compPath + "/button/" + (value == null || StringUtils.isEmpty(value) ? "on"
                        : NeeoUtil.encodeURIComponent(value.trim()));
                capabilities.add(createBase(name, channel.getLabel(), capabilityType.toString(), path));
            }
        } else if (capabilityType == NeeoCapabilityType.SENSOR_POWER) {
            final JsonObject sensorTypeObj = new JsonObject();
            sensorTypeObj.addProperty("type", NeeoCapabilityType.SENSOR_POWER.toString());

            // power should NOT use the sensor suffix
            capabilities.add(createBase(uniqueItemName, channel.getLabel(),
                    NeeoCapabilityType.SENSOR.toString(), compPath + "/switch/power", sensorTypeObj));
        } else if (capabilityType == NeeoCapabilityType.SENSOR) {
            final JsonObject sensor = new JsonObject();
            sensor.addProperty("type", NeeoCapabilityType.SENSOR_RANGE.toString());

            final NeeoDeviceChannelRange channelRange = channel.getRange();
            final int[] range = new int[] { channelRange.getMinValue(), channelRange.getMaxValue() };
            sensor.add("range", jsonContext.serialize(range));
            sensor.addProperty("unit", channelRange.getUnit());

            capabilities.add(createBase(sensorItemName, channel.getLabel(), capabilityType.toString(),
                    compPath + "/sensor/sensor", sensor));
        } else if (capabilityType == NeeoCapabilityType.SLIDER) {
            final JsonObject sliderSensor = new JsonObject();
            sliderSensor.addProperty("type", NeeoCapabilityType.SENSOR_RANGE.toString());
            sliderSensor.addProperty("sensor", sensorItemName);

            final NeeoDeviceChannelRange channelRange = channel.getRange();
            final int[] range = new int[] { channelRange.getMinValue(), channelRange.getMaxValue() };
            sliderSensor.add("range", jsonContext.serialize(range));
            sliderSensor.addProperty("unit", channelRange.getUnit());
            capabilities.add(createBase(uniqueItemName, channel.getLabel(), capabilityType.toString(),
                    compPath + "/slider/actor", "slider", sliderSensor));

            final JsonObject sensorTypeObj = new JsonObject();
            sensorTypeObj.addProperty("type", NeeoCapabilityType.SENSOR_RANGE.toString());
            sensorTypeObj.add("range", jsonContext.serialize(range));
            sensorTypeObj.addProperty("unit", channelRange.getUnit());

            capabilities.add(createBase(sensorItemName, channel.getLabel(),
                    NeeoCapabilityType.SENSOR.toString(), compPath + "/slider/sensor", sensorTypeObj));
        } else if (capabilityType == NeeoCapabilityType.SWITCH) {
            final String label = channel.getLabel();

            final NeeoButtonGroup buttons = NeeoButtonGroup.parse(label);
            if (buttons == null) {
                capabilities.add(createBase(uniqueItemName, channel.getLabel(), capabilityType.toString(),
                        compPath + "/switch/actor", new JsonPrimitive(sensorItemName)));

                final JsonObject sensorTypeObj = new JsonObject();
                sensorTypeObj.addProperty("type", NeeoCapabilityType.SENSOR_BINARY.toString());

                capabilities.add(createBase(sensorItemName, channel.getLabel(),
                        NeeoCapabilityType.SENSOR.toString(), compPath + "/switch/sensor", sensorTypeObj));
            } else {
                for (final ButtonInfo bi : buttons.getButtonInfos()) {
                    capabilities.add(createBase(bi.getLabel(), bi.getLabel(),
                            NeeoCapabilityType.BUTTON.toString(), compPath + "/button/" + bi.getSuffix()));

                }
            }
        } else if (capabilityType == NeeoCapabilityType.IMAGEURL) {
            final String value = channel.getValue();
            final String size = (value == null || StringUtils.isEmpty(value) ? "large" : value.trim())
                    .toLowerCase();

            final JsonObject jo = createBase(uniqueItemName, channel.getLabel(), capabilityType.toString(),
                    compPath + "/image/actor", "sensor", new JsonPrimitive(sensorItemName));
            jo.addProperty("size", size);
            capabilities.add(jo);

            final JsonObject sensorTypeObj = new JsonObject();
            sensorTypeObj.addProperty("type", NeeoCapabilityType.IMAGEURL.toString());

            capabilities.add(createBase(sensorItemName, channel.getLabel(),
                    NeeoCapabilityType.SENSOR.toString(), compPath + "/image/sensor", sensorTypeObj));
        } else if (capabilityType == NeeoCapabilityType.TEXTLABEL) {
            final JsonObject capObj = createBase(uniqueItemName, channel.getLabel(), capabilityType.toString(),
                    compPath + "/textlabel/actor", new JsonPrimitive(sensorItemName));

            capObj.addProperty("isLabelVisible",
                    channel instanceof NeeoDeviceChannelText
                            ? ((NeeoDeviceChannelText) channel).isLabelVisible()
                            : true);

            capabilities.add(capObj);

            final JsonObject sensorTypeObj = new JsonObject();
            sensorTypeObj.addProperty("type", NeeoCapabilityType.SENSOR_CUSTOM.toString());

            capabilities.add(createBase(sensorItemName, channel.getLabel(),
                    NeeoCapabilityType.SENSOR.toString(), compPath + "/textlabel/sensor", sensorTypeObj));
        } else if (capabilityType == NeeoCapabilityType.DIRECTORY) {
            final JsonObject capObj = createBase(uniqueItemName, channel.getLabel(), capabilityType.toString(),
                    compPath + "/directory/actor");

            capabilities.add(capObj);
        } else {
            logger.debug("Unknown capability type: {} for channel {}", capabilityType, channel);
            continue;
        }

    }
    jsonObject.add("capabilities", jsonContext.serialize(capabilities));

    return jsonObject;
}

From source file:org.openhab.io.neeo.internal.serialization.NeeoDeviceChannelSerializer.java

License:Open Source License

@Override
public JsonElement serialize(NeeoDeviceChannel chnl, @Nullable Type type,
        @Nullable JsonSerializationContext jsonContext) {
    Objects.requireNonNull(chnl, "chnl cannot be null");
    Objects.requireNonNull(type, "type cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    final JsonObject jo = new JsonObject();

    jo.add("kind", jsonContext.serialize(chnl.getKind()));
    jo.addProperty("itemName", chnl.getItemName());
    jo.addProperty("label", chnl.getLabel());
    jo.addProperty("value", chnl.getValue());
    jo.addProperty("channelNbr", chnl.getChannelNbr());
    jo.add("type", jsonContext.serialize(chnl.getType()));
    jo.add("subType", jsonContext.serialize(chnl.getSubType()));
    jo.add("range", jsonContext.serialize(chnl.getRange()));

    final ServiceContext localContext = context;
    if (localContext != null) {
        final List<String> commandTypes = new ArrayList<>();
        boolean isReadOnly = false;
        String itemLabel = chnl.getLabel();
        String itemType = null;//www  . jav a 2 s.c  o m

        try {
            final Item item = localContext.getItemRegistry().getItem(chnl.getItemName());
            itemType = item.getType();

            if (StringUtils.isNotEmpty(item.getLabel())) {
                itemLabel = item.getLabel();
            }

            for (Class<? extends Command> cmd : item.getAcceptedCommandTypes()) {
                if (!StringUtils.equalsIgnoreCase(cmd.getSimpleName(), "refreshtype")) {
                    commandTypes.add(cmd.getSimpleName().toLowerCase());
                }
            }

            for (ChannelUID channelUid : localContext.getItemChannelLinkRegistry()
                    .getBoundChannels(chnl.getItemName())) {
                if (channelUid != null) {
                    jo.addProperty("groupId", channelUid.getGroupId());
                    final Channel channel = localContext.getThingRegistry().getChannel(channelUid);
                    if (channel != null) {
                        final ChannelType channelType = localContext.getChannelTypeRegistry()
                                .getChannelType(channel.getChannelTypeUID());
                        if (channelType != null && channelType.getState() != null) {
                            isReadOnly = channelType.getState().isReadOnly();
                        }
                    }
                }
            }
        } catch (ItemNotFoundException e) {
            itemType = "N/A";
        }

        if (StringUtils.isNotEmpty(itemLabel)) {
            switch (chnl.getSubType()) {
            case HUE:
                itemType += " (Hue)";
                break;

            case SATURATION:
                itemType += " (Sat)";
                break;

            case BRIGHTNESS:
                itemType += " (Bri)";
                break;

            default:
                break;
            }
        }

        jo.addProperty("itemType", itemType);
        jo.addProperty("itemLabel", itemLabel);
        jo.add("acceptedCommandTypes", jsonContext.serialize(commandTypes));
        jo.addProperty("isReadOnly", isReadOnly);

    }

    if (chnl instanceof NeeoDeviceChannelText) {
        jo.addProperty("labelVisible", ((NeeoDeviceChannelText) chnl).isLabelVisible());
    } else if (chnl instanceof NeeoDeviceChannelDirectory) {
        jo.add("listItems", jsonContext.serialize(((NeeoDeviceChannelDirectory) chnl).getListItems()));
    }

    return jo;
}

From source file:org.openhab.io.neeo.internal.serialization.NeeoDeviceSerializer.java

License:Open Source License

@Override
public JsonElement serialize(NeeoDevice device, @Nullable Type deviceType,
        @Nullable JsonSerializationContext jsonContext) {
    Objects.requireNonNull(device, "device cannot be null");
    Objects.requireNonNull(deviceType, "deviceType cannot be null");
    Objects.requireNonNull(jsonContext, "jsonContext cannot be null");

    final JsonObject jsonObject = new JsonObject();

    final NeeoThingUID uid = device.getUid();
    jsonObject.add("uid", jsonContext.serialize(uid));
    jsonObject.add("type", jsonContext.serialize(device.getType()));
    jsonObject.addProperty("manufacturer", device.getManufacturer());
    jsonObject.addProperty("name", device.getName());
    jsonObject.addProperty("specificName", device.getSpecificName());
    jsonObject.addProperty("iconName", device.getIconName());
    jsonObject.addProperty("driverVersion", device.getDriverVersion());

    final JsonArray channels = (JsonArray) jsonContext.serialize(device.getChannels());

    final NeeoDeviceTiming timing = device.getDeviceTiming();
    jsonObject.add("timing", jsonContext.serialize(timing == null ? new NeeoDeviceTiming() : timing));

    jsonObject.add("deviceCapabilities", jsonContext.serialize(device.getDeviceCapabilities()));

    jsonObject.addProperty("thingType", uid.getThingType());

    if (StringUtils.equalsIgnoreCase(NeeoConstants.NEEOIO_BINDING_ID, uid.getBindingId())) {
        jsonObject.addProperty("thingStatus", uid.getThingType().toUpperCase());
    }// ww w. ja v a 2s .  c  o m

    final ServiceContext localContext = context;
    if (localContext != null) {
        if (!StringUtils.equalsIgnoreCase(NeeoConstants.NEEOIO_BINDING_ID, uid.getBindingId())) {
            final Thing thing = localContext.getThingRegistry().get(device.getUid().asThingUID());
            jsonObject.addProperty("thingStatus",
                    thing == null ? ThingStatus.UNKNOWN.name() : thing.getStatus().name());

            if (thing != null) {
                final ThingType thingType = localContext.getThingTypeRegistry()
                        .getThingType(thing.getThingTypeUID());

                if (thingType != null) {
                    for (JsonElement chnl : channels) {
                        JsonObject jo = (JsonObject) chnl;
                        if (jo.has("groupId") && jo.has("itemLabel")) {
                            final String groupId = jo.get("groupId").getAsString();
                            final String groupLabel = NeeoUtil.getGroupLabel(thingType, groupId);
                            if (StringUtils.isNotEmpty(groupLabel)) {
                                final JsonElement itemLabel = jo.remove("itemLabel");
                                jo.addProperty("itemLabel", groupLabel + "#" + itemLabel.getAsString());
                            } else if (StringUtils.isNotEmpty("groupId")) {
                                // have a groupid but no group definition found (usually error on binding)
                                // just default to "Others" like the Paperui does.
                                final JsonElement itemLabel = jo.remove("itemLabel");
                                jo.addProperty("itemLabel", "Others#" + itemLabel.getAsString());
                            }
                        }
                    }
                }
            }
        }
    }

    jsonObject.add("channels", channels);

    final NeeoService localService = service;
    if (localService != null) {
        List<String> foundKeys = new ArrayList<>();
        for (final NeeoBrainServlet servlet : localService.getServlets()) {
            final NeeoDeviceKeys servletKeys = servlet.getDeviceKeys();
            final Set<String> keys = servletKeys.get(device.getUid());
            foundKeys.addAll(keys);
        }
        jsonObject.add("keys", jsonContext.serialize(foundKeys));
    }

    return jsonObject;
}

From source file:org.openmrs.mobile.utilities.ResourceSerializer.java

License:Open Source License

@Override
public JsonElement serialize(Resource src, Type typeOfSrc, JsonSerializationContext context) {
    Gson myGson = getGson();//from w  w w.  ja va  2  s.com
    Gson obsGson = getObsGson();
    JsonObject srcJson = new JsonObject();
    isLocalUuid(src);

    Field[] declaredFields = src.getClass().getDeclaredFields();
    for (Field field : declaredFields) {
        if (field.getAnnotation(Expose.class) != null) {
            field.setAccessible(true);
            if (Resource.class.isAssignableFrom(field.getType())) {
                try {
                    if (field.get(src) != null) {
                        isLocalUuid((Resource) field.get(src));
                        srcJson.add(field.getName(), serializeField((Resource) field.get(src), context));
                    }
                } catch (IllegalAccessException e) {
                    Log.e(RESOURCE_SERIALIZER, EXCEPTION, e);
                }
            } else if (Collection.class.isAssignableFrom(field.getType())) {
                try {
                    Collection collection = ((Collection) field.get(src));
                    if (collection != null && !collection.isEmpty()) {
                        if (isResourceCollection(collection)) {
                            JsonArray jsonArray = new JsonArray();
                            for (Object resource : collection) {
                                isLocalUuid((Resource) resource);
                                if (((Resource) resource).getUuid() == null) {
                                    jsonArray.add(serializeField((Resource) resource, context));
                                } else {
                                    if (!(resource instanceof Observation)) {
                                        jsonArray.add(serializeField((Resource) resource, context));
                                    } else {
                                        jsonArray.add(obsGson.toJsonTree(resource));
                                    }

                                }
                            }
                            srcJson.add(field.getName(), jsonArray);
                        } else {
                            JsonArray jsonArray = new JsonArray();
                            for (Object object : collection) {
                                jsonArray.add(myGson.toJsonTree(object));
                            }
                            srcJson.add(field.getName(), jsonArray);
                        }
                    }
                } catch (IllegalAccessException e) {
                    Log.e(RESOURCE_SERIALIZER, EXCEPTION, e);
                }
            } else if (Date.class.isAssignableFrom(field.getType())) {
                try {
                    if (field.get(src) != null) {
                        srcJson.add(field.getName(),
                                context.serialize(DateUtils.convertTime(((Date) field.get(src)).getTime(),
                                        DateUtils.OPEN_MRS_REQUEST_FORMAT)));
                    }
                } catch (IllegalAccessException e) {
                    Log.e(RESOURCE_SERIALIZER, EXCEPTION, e);
                }
            } else {
                try {
                    srcJson.add(field.getName(), myGson.toJsonTree(field.get(src)));
                } catch (IllegalAccessException e) {
                    Log.e(RESOURCE_SERIALIZER, EXCEPTION, e);
                }
            }
        }
    }
    return srcJson;
}

From source file:org.openmrs.mobile.utilities.ResourceSerializer.java

License:Open Source License

private JsonElement serializeField(Resource src, JsonSerializationContext context) {
    if (src.getUuid() != null) {
        return new JsonPrimitive(src.getUuid());
    } else {// ww w. j a va2 s.  com
        return context.serialize(src);
    }
}

From source file:org.quartzpowered.protocol.data.chat.component.serialize.BaseComponentSerializer.java

License:Open Source License

protected void serialize(JsonObject object, BaseComponent component, JsonSerializationContext context) {
    boolean first = false;
    if (ComponentSerializer.serializedComponents.get() == null) {
        first = true;// w ww  .j  av  a2s.  c  o m
        ComponentSerializer.serializedComponents.set(new HashSet<BaseComponent>());
    }
    try {
        Preconditions.checkArgument(!ComponentSerializer.serializedComponents.get().contains(component),
                "Component loop");
        ComponentSerializer.serializedComponents.get().add(component);
        if (component.getColorRaw() != null) {
            object.addProperty("color", component.getColorRaw().getName());
        }
        if (component.isBoldRaw() != null) {
            object.addProperty("bold", component.isBoldRaw());
        }
        if (component.isItalicRaw() != null) {
            object.addProperty("italic", component.isItalicRaw());
        }
        if (component.isUnderlinedRaw() != null) {
            object.addProperty("underlined", component.isUnderlinedRaw());
        }
        if (component.isStrikethroughRaw() != null) {
            object.addProperty("strikethrough", component.isStrikethroughRaw());
        }
        if (component.isObfuscatedRaw() != null) {
            object.addProperty("obfuscated", component.isObfuscatedRaw());
        }

        if (component.getExtra() != null) {
            object.add("extra", context.serialize(component.getExtra()));
        }

        //Events
        if (component.getClickEvent() != null) {
            JsonObject clickEvent = new JsonObject();
            clickEvent.addProperty("action", component.getClickEvent().getAction().toString().toLowerCase());
            clickEvent.addProperty("value", component.getClickEvent().getValue());
            object.add("clickEvent", clickEvent);
        }
        if (component.getHoverEvent() != null) {
            JsonObject hoverEvent = new JsonObject();
            hoverEvent.addProperty("action", component.getHoverEvent().getAction().toString().toLowerCase());
            hoverEvent.add("value", context.serialize(component.getHoverEvent().getValue()));
            object.add("hoverEvent", hoverEvent);
        }
    } finally {
        ComponentSerializer.serializedComponents.get().remove(component);
        if (first) {
            ComponentSerializer.serializedComponents.set(null);
        }
    }
}