Search in sources :

Example 91 with JsonElement

use of com.google.gson.JsonElement in project Smartcity-Smarthouse by TechnionYP5777.

the class Savable method populate.

/**
     * Populates the object with data from the jsonString.
     * <p>
     * Only fields without {@link Expose} Annotation will be populated.
     * <p>
     * <code>Populate</code> will be called recursively for fields that also
     * implement {@link Savable}<br>
     * (not including collections).
     * <p>
     * Override this function in order to define what to do after
     * populating.<br>
     * You should still call <code>Savable.super.populate(jsonString);</code>
     * 
     * @param jsonString
     * @throws Exception
     */
default default void populate(final String jsonString) throws Exception {
    for (final Entry<String, JsonElement> e : new JsonParser().parse(jsonString).getAsJsonObject().entrySet()) {
        final Field f = getClass().getDeclaredField(e.getKey());
        f.setAccessible(true);
        if (Savable.class.isAssignableFrom(f.getType()))
            ((Savable) f.get(this)).populate(e.getValue() + "");
        else
            f.set(this, gsonBuilder.create().fromJson(e.getValue(), f.getGenericType()));
    }
}
Also used : Field(java.lang.reflect.Field) JsonElement(com.google.gson.JsonElement) JsonParser(com.google.gson.JsonParser)

Example 92 with JsonElement

use of com.google.gson.JsonElement in project groupme-utils by TheGuyWithTheFace.

the class GroupDeserializer method deserialize.

@Override
public Group deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonObject json = getResponse(jsonElement).getAsJsonObject();
    GroupBuilder g = new GroupBuilder();
    g.setId(json.get("id").getAsString());
    g.setName(json.get("name").getAsString());
    g.setType(json.get("type").getAsString());
    g.setDescription(json.get("description").getAsString());
    if (!json.get("image_url").isJsonNull()) {
        g.setImageUrl(json.get("image_url").getAsString());
    }
    g.setCreatorUserId(json.get("creator_user_id").getAsString());
    long createTime = json.get("created_at").getAsLong();
    g.setCreatedAt(Instant.ofEpochSecond(createTime));
    long updateTime = json.get("updated_at").getAsLong();
    g.setUpdatedAt(Instant.ofEpochSecond(updateTime));
    if (!json.get("share_url").isJsonNull()) {
        g.setShareUrl(json.get("share_url").getAsString());
    }
    // Get members of the group
    JsonArray response = json.get("members").getAsJsonArray();
    int numMembers = response.size();
    Member[] members = new Member[numMembers];
    for (int i = 0; i < numMembers; i++) {
        JsonElement elem = response.get(i);
        members[i] = context.deserialize(elem, Member.class);
    }
    g.setMembers(members);
    // TODO this will be reworked later, see note in Group Class.
    JsonObject messages = json.get("messages").getAsJsonObject();
    g.setMessageCount(messages.get("count").getAsInt());
    g.setLastMessageId(messages.get("last_message_id").getAsString());
    long lastCreate = messages.get("last_message_created_at").getAsLong();
    g.setLastMessageCreatedAt(Instant.ofEpochSecond(lastCreate));
    return g.createGroup();
}
Also used : JsonArray(com.google.gson.JsonArray) JsonElement(com.google.gson.JsonElement) GroupBuilder(me.perrycate.groupmeutils.data.GroupBuilder) JsonObject(com.google.gson.JsonObject) Member(me.perrycate.groupmeutils.data.Member)

Example 93 with JsonElement

use of com.google.gson.JsonElement in project groupme-utils by TheGuyWithTheFace.

the class GroupArrayDeserializer method deserialize.

public Group[] deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonArray response = getResponse(jsonElement).getAsJsonArray();
    // Deserialize one group at a time, add to new groups array.
    int numGroups = response.size();
    Group[] groups = new Group[numGroups];
    for (int i = 0; i < numGroups; i++) {
        JsonElement elem = response.get(i);
        groups[i] = context.deserialize(elem, Group.class);
    }
    return groups;
}
Also used : JsonArray(com.google.gson.JsonArray) Group(me.perrycate.groupmeutils.data.Group) JsonElement(com.google.gson.JsonElement)

Example 94 with JsonElement

use of com.google.gson.JsonElement in project Engine by VoltzEngine-Project.

the class RenderJsonProcessor method process.

@Override
public RenderData process(JsonElement element) {
    final JsonObject object = element.getAsJsonObject();
    ensureValuesExist(object, "contentID", "states", "type");
    String contentID = object.get("contentID").getAsString();
    String overAllRenderType = object.get("type").getAsString();
    RenderData data;
    if (overAllRenderType.equalsIgnoreCase("tile")) {
        data = new TileRenderData(this, contentID, overAllRenderType);
        if (object.has("tileClass")) {
            try {
                ((TileRenderData) data).tileClass = (Class<? extends TileEntity>) Class.forName(object.get("tileClass").getAsString());
            } catch (Exception e) {
                throw new IllegalArgumentException("Failed to load class for name '" + object.get("tileClass").getAsString() + "'");
            }
        }
    } else {
        data = new RenderData(this, contentID, overAllRenderType);
    }
    JsonArray array = object.get("states").getAsJsonArray();
    for (JsonElement arrayElement : array) {
        if (arrayElement instanceof JsonObject) {
            JsonObject renderStateObject = arrayElement.getAsJsonObject();
            //For loop handling for the lazy
            if (renderStateObject.has("for")) {
                renderStateObject = renderStateObject.getAsJsonObject("for");
                ensureValuesExist(renderStateObject, "start", "end", "state");
                int start = renderStateObject.getAsJsonPrimitive("start").getAsInt();
                int end = renderStateObject.getAsJsonPrimitive("end").getAsInt();
                if (start >= end) {
                    throw new IllegalArgumentException("Start can not be greater than or equal to end for a for loop.");
                }
                JsonObject template = renderStateObject.getAsJsonObject("state");
                for (int i = start; i <= end; i++) {
                    JsonObject state = new JsonObject();
                    //Copy template and rename values as needed
                    for (Map.Entry<String, JsonElement> entry : template.entrySet()) {
                        if (entry.getValue() instanceof JsonPrimitive && ((JsonPrimitive) entry.getValue()).isString()) {
                            String s = entry.getValue().getAsString();
                            s = s.replace("%number%", "" + i);
                            state.add(entry.getKey(), new JsonPrimitive(s));
                        } else {
                            state.add(entry.getKey(), entry.getValue());
                        }
                    }
                    //Load state
                    handle(state, data, overAllRenderType);
                }
            } else {
                handle(renderStateObject, data, overAllRenderType);
            }
        }
    }
    //Handle post calls
    for (IRenderState state : data.renderStatesByName.values()) {
        //Handles post processor actions
        if (stateToProcessor.containsKey(state)) {
            stateToProcessor.get(state).postHandle(state, data);
        }
    }
    //Clear run data
    stateToProcessor.clear();
    //TODO ensure modelID exists if model state
    return data;
}
Also used : JsonPrimitive(com.google.gson.JsonPrimitive) TileRenderData(com.builtbroken.mc.client.json.render.tile.TileRenderData) JsonObject(com.google.gson.JsonObject) JsonArray(com.google.gson.JsonArray) RenderData(com.builtbroken.mc.client.json.render.RenderData) TileRenderData(com.builtbroken.mc.client.json.render.tile.TileRenderData) JsonElement(com.google.gson.JsonElement) IRenderState(com.builtbroken.mc.client.json.imp.IRenderState) HashMap(java.util.HashMap) Map(java.util.Map)

Example 95 with JsonElement

use of com.google.gson.JsonElement in project Engine by VoltzEngine-Project.

the class JsonBlockListenerProcessor method process.

@Override
public void process(BlockBase block, JsonElement arrayElement, List<IJsonGenObject> objectList) {
    JsonArray array = arrayElement.getAsJsonArray();
    for (JsonElement element : array) {
        String key = null;
        JsonObject data = null;
        if (element.isJsonPrimitive()) {
            key = element.getAsString().toLowerCase();
        } else if (element.isJsonObject()) {
            JsonObject object = element.getAsJsonObject();
            JsonProcessor.ensureValuesExist(object, "id");
            key = object.get("id").getAsString().toLowerCase();
            data = object;
        }
        if (builders.containsKey(key)) {
            ITileEventListener listener = builders.get(key).createListener(block);
            if (listener != null) {
                if (data != null) {
                    if (!injectionMaps.containsKey(listener.getClass())) {
                        injectionMaps.put(listener.getClass(), new JsonProcessorInjectionMap(listener.getClass()));
                    }
                    JsonProcessorInjectionMap injectionMap = injectionMaps.get(listener.getClass());
                    for (Map.Entry<String, JsonElement> entry : data.entrySet()) {
                        injectionMap.handle(listener, entry.getKey(), entry.getValue());
                    }
                }
                block.addListener(listener);
            }
        }
    }
}
Also used : JsonArray(com.google.gson.JsonArray) JsonElement(com.google.gson.JsonElement) ITileEventListener(com.builtbroken.mc.api.tile.listeners.ITileEventListener) JsonObject(com.google.gson.JsonObject) JsonProcessorInjectionMap(com.builtbroken.mc.lib.json.loading.JsonProcessorInjectionMap) HashMap(java.util.HashMap) JsonProcessorInjectionMap(com.builtbroken.mc.lib.json.loading.JsonProcessorInjectionMap) Map(java.util.Map)

Aggregations

JsonElement (com.google.gson.JsonElement)682 JsonObject (com.google.gson.JsonObject)381 JsonArray (com.google.gson.JsonArray)166 JsonPrimitive (com.google.gson.JsonPrimitive)107 JsonParser (com.google.gson.JsonParser)105 Gson (com.google.gson.Gson)69 Map (java.util.Map)63 ArrayList (java.util.ArrayList)51 HashMap (java.util.HashMap)50 IOException (java.io.IOException)48 Test (org.testng.annotations.Test)45 JsonReader (com.google.gson.stream.JsonReader)31 InputStreamReader (java.io.InputStreamReader)28 GsonBuilder (com.google.gson.GsonBuilder)26 Pager (com.willshex.blogwt.shared.api.Pager)26 Type (java.lang.reflect.Type)25 StringReader (java.io.StringReader)21 Test (org.junit.Test)21 User (com.willshex.blogwt.shared.api.datatype.User)19 JsonParseException (com.google.gson.JsonParseException)17