Example usage for com.google.gson JsonElement getAsString

List of usage examples for com.google.gson JsonElement getAsString

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:com.ecwid.mailchimp.MailChimpClient.java

License:Apache License

/**
 * Execute MailChimp API method./*www  .  j a v  a2 s  .  c  o  m*/
 * 
 * @param method MailChimp API method to be executed
 * @return execution result
 */
public <R> R execute(MailChimpMethod<R> method) throws IOException, MailChimpException {
    final Gson gson = MailChimpGsonFactory.createGson();

    JsonElement result = execute(buildUrl(method), gson.toJsonTree(method));
    if (result.isJsonObject()) {
        JsonElement error = result.getAsJsonObject().get("error");
        if (error != null) {
            JsonElement code = result.getAsJsonObject().get("code");
            throw new MailChimpException(code.getAsInt(), error.getAsString());
        }
    }

    return gson.fromJson(result, method.getResultType());
}

From source file:com.edu.mum.hbs.restapi.util.LocalTimeConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during deserialization when it encounters a field of the
 * specified type. <p>/*from  w  w  w  .  j  a v a2  s.c  om*/
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects
 * for any non-trivial field of the returned object. However, you should never invoke it on the
 * the same type passing {@code json} since that will cause an infinite loop (Gson will call your
 * call-back method again).
 *
 * @param json The Json data being deserialized
 * @param typeOfT The type of the Object to deserialize to
 * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T}
 * @throws JsonParseException if json is not in the expected format of {@code typeOfT}
 */
@Override
public LocalTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return FORMATTER.parse(json.getAsString(), LocalTime::from);
}

From source file:com.elevenpaths.srv.LatchSrv.java

public String solicitarToken(String token) throws ServiceException {
    LatchResponse pairResponse = latch.pair(token);
    String codigoPareado = null;/*  ww w .j a  v  a2  s .  co  m*/
    if (pairResponse.getError() == null) {
        //this.codigoPareado = pairResponse.getData().entrySet().toArray()[0];
        //accountId => "ZeQ8PvnmB9L4hhKRLUkdcjLn7amBU9bn2rAjMRGHwTrR4QUzGgPxTY2PpQ8vbzgZ"
        //accountId => "TUan4VbQF2zvmZC9jEfh7BYaUJ7NppcGh27XePW4a9ARLz3G2HJYd3N7rtceUyxi"
        JsonElement element = pairResponse.getData().get("accountId");
        codigoPareado = element.getAsString();
        System.out.print("Codigo pareado " + codigoPareado);
    } else {
        throw new ServiceException(pairResponse.getError().getCode() + "",
                pairResponse.getError().getMessage());
    }
    return codigoPareado;
}

From source file:com.elevenpaths.srv.LatchSrv.java

private static boolean estaActivo(LatchResponse statusResponse) {
    //operations => {"cKbvzaZ6TYUWCCMsNUBU":{"status":"off"}}
    boolean salida = false;
    JsonElement operations = statusResponse.getData().get("operations");
    Set<Map.Entry<String, JsonElement>> keys = operations.getAsJsonObject().entrySet();
    for (Iterator<Map.Entry<String, JsonElement>> iterator = keys.iterator(); iterator.hasNext();) {
        Map.Entry<String, JsonElement> key = iterator.next();
        JsonElement status = key.getValue().getAsJsonObject().get("status");
        if ("on".equals(status.getAsString())) {
            salida = true;//from w  ww .j  ava 2  s. c om
        }
    }
    return salida;
}

From source file:com.emc.ecs.sync.model.ObjectMetadata.java

License:Open Source License

public static ObjectMetadata fromJson(String json) {
    JsonObject root = new JsonParser().parse(json).getAsJsonObject();
    JsonElement instanceClass = root.get("instanceClass");
    if (instanceClass == null) { // might be data from an older version; make sure user is aware
        throw new RuntimeException(
                "could not parse meta-file. this could mean you used an older version of EcsSync to move data to the source location. either use that same version again or use --no-sync-user-metadata to continue using this version");
    } else {/*from   w w w  .  j a v a  2s . com*/
        try {
            return ((ObjectMetadata) Class.forName(instanceClass.getAsString()).newInstance())
                    .createFromJson(json);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:com.emc.ecs.sync.model.SyncMetadata.java

License:Open Source License

public static SyncMetadata fromJson(String json) {
    JsonObject root = new JsonParser().parse(json).getAsJsonObject();
    JsonElement instanceClass = root.get("instanceClass");
    if (instanceClass == null) { // might be data from an older version; make sure user is aware
        throw new RuntimeException(
                "could not parse meta-file. this could mean you used an older version of EcsSync to move data to the source location. either use that same version again or use --"
                        + CommonOptions.IGNORE_METADATA_OPTION + " to continue using this version");
    } else {/*w  w  w . ja v  a2s.co m*/
        try {
            return ((SyncMetadata) Class.forName(instanceClass.getAsString()).newInstance())
                    .createFromJson(json);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:com.ephemeraldreams.gallyshuttle.data.LocalTimeSerializer.java

License:Apache License

@Override
public LocalTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return FORMATTER.parseLocalTime(json.getAsString());
}

From source file:com.epishie.tabs.gson.ThingDeserializer.java

License:Apache License

@Override
public Thing deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Expected json object");
    }/*  w ww. j  a  v a 2s.co  m*/
    JsonObject jsonObject = json.getAsJsonObject();
    if (!jsonObject.has(KIND)) {
        throw new JsonParseException("Expected to have \"kind\" field");
    }
    JsonElement kindElement = jsonObject.get(KIND);
    if (!kindElement.isJsonPrimitive()) {
        throw new JsonParseException("Expected to have a primitive \"kind\" field");
    }
    if (!jsonObject.has(DATA)) {
        throw new JsonParseException("Expected to have a\"data\" field");
    }
    String kind = kindElement.getAsString();
    String id = null;
    String name = null;
    if (jsonObject.has(ID)) {
        JsonElement idElement = jsonObject.get(ID);
        id = idElement.getAsString();
    }
    if (jsonObject.has(NAME)) {
        JsonElement nameElement = jsonObject.get(NAME);
        name = nameElement.getAsString();
    }
    Thing thing = null;
    switch (kind) {
    case Link.KIND:
        Link link = context.deserialize(jsonObject.get(DATA), Link.class);
        thing = new Thing<>(id, name, link);
        break;
    case Listing.KIND:
        Listing listing = context.deserialize(jsonObject.get(DATA), Listing.class);
        // noinspection unchecked
        thing = new Thing(id, name, listing);
        break;
    case Subreddit.KIND:
        Subreddit subreddit = context.deserialize(jsonObject.get(DATA), Subreddit.class);
        // noinspection unchecked
        thing = new Thing(id, name, subreddit);
        break;
    case Comment.KIND:
        Comment comment = context.deserialize(jsonObject.get(DATA), Comment.class);
        // noinspection unchecked
        thing = new Thing(id, name, comment);
        break;
    }
    return thing;
}

From source file:com.esotericsoftware.spine.SkeletonJson.java

License:Open Source License

public SkeletonData readSkeletonData(String folder, String file) {
    float scale = this.scale;

    SkeletonData skeletonData = new SkeletonData();
    //skeletonData.name = file.nameWithoutExtension();
    skeletonData.name = file;//from  w w  w  .  j  ava2s.  co  m

    //JsonValue root = new JsonReader().parse(file);
    try (InputStreamReader isReader = new InputStreamReader(
            ResourceLoader.getResourceAsStream(folder + "/" + file + ".json"))) {
        JsonReader reader = new JsonReader(isReader);
        JsonParser parser = new JsonParser();

        JsonObject root = (JsonObject) parser.parse(reader);

        // Skeleton.
        JsonObject skeletonMap = root.get("skeleton").getAsJsonObject();
        if (skeletonMap != null) {
            skeletonData.hash = skeletonMap.has("hash") ? skeletonMap.get("hash").getAsString() : null;
            skeletonData.version = skeletonMap.has("spine") ? skeletonMap.get("spine").getAsString() : null;
            skeletonData.width = skeletonMap.has("width") ? skeletonMap.get("width").getAsFloat() : 0;
            skeletonData.height = skeletonMap.has("height") ? skeletonMap.get("height").getAsFloat() : 0;
            skeletonData.imagesPath = skeletonMap.has("images") ? skeletonMap.get("images").getAsString()
                    : null;
        }

        // Bones.
        //for (JsonValue boneMap = root.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
        for (JsonElement boneMap : root.get("bones").getAsJsonArray()) {
            JsonObject currentBone = boneMap.getAsJsonObject();
            BoneData parent = null;
            String parentName = currentBone.has("parent") ? currentBone.get("parent").getAsString() : null;
            if (parentName != null) {
                parent = skeletonData.findBone(parentName);
                if (parent == null)
                    throw new SerializationException("Parent bone not found: " + parentName);
            }
            BoneData boneData = new BoneData(currentBone.get("name").getAsString(), parent);
            boneData.length = (currentBone.has("length") ? currentBone.get("length").getAsFloat() : 0) * scale;//boneMap.getFloat("length", 0) * scale;
            boneData.x = (currentBone.has("x") ? currentBone.get("x").getAsFloat() : 0) * scale;//boneMap.getFloat("x", 0) * scale;
            boneData.y = (currentBone.has("y") ? currentBone.get("y").getAsFloat() : 0) * scale;//boneMap.getFloat("y", 0) * scale;
            boneData.rotation = currentBone.has("rotation") ? currentBone.get("rotation").getAsFloat() : 0;//boneMap.getFloat("rotation", 0);
            boneData.scaleX = currentBone.has("scaleX") ? currentBone.get("scaleX").getAsFloat() : 1;//boneMap.getFloat("scaleX", 1);
            boneData.scaleY = currentBone.has("scaleY") ? currentBone.get("scaleY").getAsFloat() : 1;//boneMap.getFloat("scaleY", 1);
            boneData.flipX = currentBone.has("flipX") ? currentBone.get("flipX").getAsBoolean() : false;//boneMap.getBoolean("flipX", false);
            boneData.flipY = currentBone.has("flipY") ? currentBone.get("flipY").getAsBoolean() : false;//boneMap.getBoolean("flipY", false);
            boneData.inheritScale = currentBone.has("inheritScale")
                    ? currentBone.get("inheritScale").getAsBoolean()
                    : true;//boneMap.getBoolean("inheritScale", true);
            boneData.inheritRotation = currentBone.has("inheritRotation")
                    ? currentBone.get("inheritRotation").getAsBoolean()
                    : true;//boneMap.getBoolean("inheritRotation", true);

            String color = currentBone.has("color") ? currentBone.get("color").getAsString() : null;//boneMap.getString("color", null);
            if (color != null)
                boneData.getColor().set(Color.valueOf(color));

            skeletonData.bones.add(boneData);
        }

        // IK constraints.
        // TODO May return a JsonObject not Array
        //for (JsonValue ikMap = root.getChild("ik"); ikMap != null; ikMap = ikMap.next) {
        if (root.has("ik")) {
            for (JsonElement ikMap : root.get("ik").getAsJsonArray()) {
                JsonObject currentIk = ikMap.getAsJsonObject();
                IkConstraintData ikConstraintData = new IkConstraintData(currentIk.get("name").getAsString());

                //for (JsonValue boneMap = ikMap.getChild("bones"); boneMap != null; boneMap = boneMap.next) {
                for (JsonElement boneMap : currentIk.get("bones").getAsJsonArray()) {
                    String boneName = boneMap.getAsString();
                    BoneData bone = skeletonData.findBone(boneName);
                    if (bone == null)
                        throw new SerializationException("IK bone not found: " + boneName);
                    ikConstraintData.bones.add(bone);
                }

                String targetName = currentIk.get("target").getAsString();
                ikConstraintData.target = skeletonData.findBone(targetName);
                if (ikConstraintData.target == null)
                    throw new SerializationException("Target bone not found: " + targetName);

                ikConstraintData.bendDirection = (currentIk.has("bendPositive")
                        ? currentIk.get("bendPositive").getAsBoolean()
                        : true) ? 1 : -1;//ikMap.getBoolean("bendPositive", true) ? 1 : -1;
                ikConstraintData.mix = currentIk.has("mix") ? currentIk.get("mix").getAsFloat() : 1;//ikMap.getFloat("mix", 1);

                skeletonData.ikConstraints.add(ikConstraintData);
            }
        }

        // Slots.
        //for (JsonValue slotMap = root.getChild("slots"); slotMap != null; slotMap = slotMap.next) {
        for (JsonElement slotMap : root.get("slots").getAsJsonArray()) {
            JsonObject currentSlot = slotMap.getAsJsonObject();
            String slotName = currentSlot.get("name").getAsString();
            String boneName = currentSlot.get("bone").getAsString();
            BoneData boneData = skeletonData.findBone(boneName);
            if (boneData == null)
                throw new SerializationException("Slot bone not found: " + boneName);
            SlotData slotData = new SlotData(slotName, boneData);

            String color = currentSlot.has("color") ? currentSlot.get("color").getAsString() : null;//slotMap.getString("color", null);
            if (color != null)
                slotData.getColor().set(Color.valueOf(color));

            slotData.attachmentName = currentSlot.has("attachment")
                    ? currentSlot.get("attachment").getAsString()
                    : null;//slotMap.getString("attachment", null);

            slotData.additiveBlending = currentSlot.has("additive") ? currentSlot.get("additive").getAsBoolean()
                    : false;//slotMap.getBoolean("additive", false);

            skeletonData.slots.add(slotData);
        }

        // Skins.
        //for (JsonValue skinMap = root.getChild("skins"); skinMap != null; skinMap = skinMap.next) {
        for (Entry<String, JsonElement> skinMap : root.get("skins").getAsJsonObject().entrySet()) {
            Skin skin = new Skin(skinMap.getKey());
            //for (JsonValue slotEntry = skinMap.child; slotEntry != null; slotEntry = slotEntry.next) {
            for (Entry<String, JsonElement> slotEntry : skinMap.getValue().getAsJsonObject().entrySet()) {
                int slotIndex = skeletonData.findSlotIndex(slotEntry.getKey());
                if (slotIndex == -1)
                    throw new SerializationException("Slot not found: " + slotEntry.getKey());
                //for (JsonValue entry = slotEntry.child; entry != null; entry = entry.next) {
                for (Entry<String, JsonElement> entry : slotEntry.getValue().getAsJsonObject().entrySet()) {
                    Attachment attachment = readAttachment(skin, entry.getKey(),
                            entry.getValue().getAsJsonObject());
                    if (attachment != null) {
                        skin.addAttachment(slotIndex, entry.getKey(), attachment);
                    }
                }
            }
            skeletonData.skins.add(skin);
            if (skin.name.equals("default"))
                skeletonData.defaultSkin = skin;
        }

        // Events.
        //for (JsonValue eventMap = root.getChild("events"); eventMap != null; eventMap = eventMap.next) {
        if (root.has("events")) {
            for (Entry<String, JsonElement> eventMap : root.get("events").getAsJsonObject().entrySet()) {
                JsonObject currentEvent = eventMap.getValue().getAsJsonObject();
                EventData eventData = new EventData(eventMap.getKey());
                eventData.intValue = currentEvent.has("int") ? currentEvent.get("int").getAsInt() : 0;//eventMap.getInt("int", 0);
                eventData.floatValue = currentEvent.has("float") ? currentEvent.get("float").getAsFloat() : 0f;//eventMap.getFloat("float", 0f);
                eventData.stringValue = currentEvent.has("string") ? currentEvent.get("string").getAsString()
                        : null;//eventMap.getString("string", null);
                skeletonData.events.add(eventData);
            }
        }

        // Animations.
        //for (JsonValue animationMap = root.getChild("animations"); animationMap != null; animationMap = animationMap.next)
        for (Entry<String, JsonElement> animationMap : root.get("animations").getAsJsonObject().entrySet()) {
            readAnimation(animationMap.getKey(), animationMap.getValue().getAsJsonObject(), skeletonData);
        }

    } catch (JsonIOException | IOException e) {
        e.printStackTrace();
    }

    /*skeletonData.bones.shrink();
    skeletonData.slots.shrink();
    skeletonData.skins.shrink();
    skeletonData.animations.shrink();*/
    return skeletonData;
}

From source file:com.esotericsoftware.spine.SkeletonJson.java

License:Open Source License

void readCurve(CurveTimeline timeline, int frameIndex, JsonObject valueMap) {
    JsonElement curve = valueMap.has("curve") ? valueMap.get("curve") : null;
    if (curve == null)
        return;/*from w w w  . ja va 2  s  .  c  o  m*/
    if (curve.isJsonPrimitive() && curve.getAsString().equals("stepped"))
        timeline.setStepped(frameIndex);
    else if (curve.isJsonArray()) {
        JsonArray curveArray = curve.getAsJsonArray();
        timeline.setCurve(frameIndex, curveArray.get(0).getAsFloat(), curveArray.get(1).getAsFloat(),
                curveArray.get(2).getAsFloat(), curveArray.get(3).getAsFloat());
    }
}