Example usage for com.google.gson JsonElement getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive() 

Source Link

Document

convenience method to get this element as a JsonPrimitive .

Usage

From source file:de.azapps.mirakel.model.list.meta.SetDeserializer.java

License:Open Source License

@Override
public T deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) {
    if (json.isJsonObject()) {
        List<Integer> content = null;
        Boolean negated = null;// initialize with stuff to mute the
        // compiler
        for (final Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {

            if (entry.getValue().isJsonArray() && "content".equals(entry.getKey())) {
                content = new ArrayList<>(entry.getValue().getAsJsonArray().size());
                for (final JsonElement el : ((JsonArray) entry.getValue())) {
                    if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isNumber()) {
                        content.add(el.getAsInt());
                    }//from w ww .java2 s. co m
                }
            } else if (entry.getValue().isJsonPrimitive()
                    && ("isNegated".equals(entry.getKey()) || "isSet".equals(entry.getKey()))) {
                negated = entry.getValue().getAsBoolean();
            } else {
                throw new JsonParseException("unknown format");
            }
        }
        if ((content != null) && (negated != null)) {
            try {
                return (T) clazz.getConstructor(boolean.class, List.class).newInstance(negated, content);
            } catch (IllegalAccessException | InstantiationException | NoSuchMethodException
                    | InvocationTargetException e) {
                throw new JsonParseException("Could not create new SetProperty", e);
            }

        }
    }
    throw new JsonParseException("unknown format");
}

From source file:de.azapps.mirakel.sync.taskwarrior.model.TaskWarriorTaskDeserializer.java

License:Open Source License

@Override
public TaskWarriorTask deserialize(final JsonElement json, final Type type,
        final JsonDeserializationContext ctx) throws JsonParseException {
    final JsonObject el = json.getAsJsonObject();
    final JsonElement uuid = el.get("uuid");
    final JsonElement status = el.get("status");
    final JsonElement entry = el.get("entry");
    final JsonElement description = el.get("description");
    if (uuid == null || status == null || entry == null || description == null || !uuid.isJsonPrimitive()
            || !status.isJsonPrimitive() || !entry.isJsonPrimitive() || !description.isJsonPrimitive()
            || !uuid.getAsJsonPrimitive().isString() || !status.getAsJsonPrimitive().isString()
            || !entry.getAsJsonPrimitive().isString() || !description.getAsJsonPrimitive().isString()) {
        throw new JsonParseException("Invalid syntax, missing required field");
    }//w  w w  .  ja  v  a  2s  .c  om
    final TaskWarriorTask task = new TaskWarriorTask(uuid.getAsString(), status.getAsString(),
            parseDate(entry.getAsString()), description.getAsString());
    for (final Entry<String, JsonElement> element : el.entrySet()) {
        switch (element.getKey()) {
        case "uuid":
        case "description":
        case "entry":
        case "status":
            break;
        case "priority":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setPriority(element.getValue().getAsString());
            } else {
                throw new JsonParseException("priority is not a json primitive");
            }
            break;
        case "priorityNumber":
            // taskd does not handle numbers in the right way
            if (element.getValue().isJsonPrimitive()) {
                task.setPriorityNumber((int) element.getValue().getAsDouble());
            } else {
                throw new JsonParseException("priority is not a json primitive");
            }
            break;
        case "progress":
            // taskd does not handle numbers in the right way
            if (element.getValue().isJsonPrimitive()) {
                task.setProgress((int) element.getValue().getAsDouble());
            } else {
                throw new JsonParseException("progress is not a json primitive");
            }
            break;
        case "project":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setProject(element.getValue().getAsString());
            } else {
                throw new JsonParseException("project is not a json primitive");
            }
            break;
        case "modification":
        case "modified":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setModified(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("modified is not a json primitive");
            }
            break;
        case "due":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setDue(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("due is not a json primitive");
            }
            break;
        case "reminder":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setReminder(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("reminder is not a json primitive");
            }
            break;
        case "annotations":
            if (element.getValue().isJsonArray()) {
                final JsonArray annotations = element.getValue().getAsJsonArray();
                for (int i = 0; i < annotations.size(); i++) {
                    if (annotations.get(i).isJsonObject()) {
                        final JsonElement descr = annotations.get(i).getAsJsonObject().get("description");
                        final JsonElement annotationEntry = annotations.get(i).getAsJsonObject().get("entry");
                        if (descr == null || annotationEntry == null || !descr.isJsonPrimitive()
                                || !annotationEntry.isJsonPrimitive() || !descr.getAsJsonPrimitive().isString()
                                || !annotationEntry.getAsJsonPrimitive().isString()) {
                            throw new JsonParseException("Annotation is not valid");
                        } else {
                            task.addAnnotation(descr.getAsString(), parseDate(annotationEntry.getAsString()));
                        }
                    } else {
                        throw new JsonParseException("Annotation is not a json object");
                    }
                }
            } else {
                throw new JsonParseException("annotations is not a json array");
            }
            break;
        case "depends":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                final String depends = element.getValue().getAsString();
                task.addDepends(depends.split(","));
            } else {
                throw new JsonParseException("depends is not a json primitive");
            }
            break;
        case "tags":
            if (element.getValue().isJsonArray()) {
                final JsonArray tags = element.getValue().getAsJsonArray();
                for (int i = 0; i < tags.size(); i++) {
                    if (tags.get(i).isJsonPrimitive() && tags.get(i).getAsJsonPrimitive().isString()) {
                        task.addTags(tags.get(i).getAsString());
                    } else {
                        throw new JsonParseException("tag is not a string");
                    }
                }
            } else {
                throw new JsonParseException("tags is not a json array");
            }
            break;
        case "recur":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setRecur(element.getValue().getAsString());
            } else {
                throw new JsonParseException("recur is not a json primitive");
            }
            break;
        case "imask":
            if (element.getValue().isJsonPrimitive()) {
                task.setImask((int) element.getValue().getAsDouble());
            } else {
                throw new JsonParseException("imask is not a json primitive");
            }
            break;
        case "parent":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setParent(element.getValue().getAsString());
            } else {
                throw new JsonParseException("parent is not a json primitive");
            }
            break;
        case "mask":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setMask(element.getValue().getAsString());
            } else {
                throw new JsonParseException("mask is not a json primitive");
            }
            break;
        case "until":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setUntil(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("until is not a json primitive");
            }
            break;
        default:
            task.addUDA(element.getKey(), element.getValue().getAsString());
            break;
        }
    }

    return task;
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

@Override
public UserInfo getUserInfo(String userName) throws UserNotExistException {
    try {/* w w w .ja  va2s.c om*/
        final int userid = this.getUserID(userName);

        if (userid == -1) {
            /* article does not exist */
            throw new UserNotExistException("Nutzer \"" + userid + "\" existiert nicht!");
        }

        final List<UserInfo.ArticleEdited> categoryEdited = new ArrayList<UserInfo.ArticleEdited>();

        boolean isBot = false;
        Date signInDate = null;
        int lastUserCommits = 0;

        final String response1 = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=users&ususers=" + userName
                        + "&usprop=editcount|registration|blockinfo|groups"));

        final JsonObject root = this.parser.parse(response1).getAsJsonObject();
        final JsonObject user = root.getAsJsonObject("query").getAsJsonArray("users").get(0).getAsJsonObject();

        if (user.has("groups")) {
            final JsonArray groupsJsonArr = user.getAsJsonArray("groups");
            for (JsonElement jsonElement : groupsJsonArr) {
                if ("bot".equals(jsonElement.getAsJsonPrimitive().getAsString())) {
                    isBot = true;
                    break;
                }
            }
        }

        final int editcount = user.getAsJsonPrimitive("editcount").getAsInt();

        final boolean blocked = user.has("blockid");

        Map<Tuple2<Integer, String>, Tuple2<Integer, Integer>> comparableRevisions = new HashMap<Tuple2<Integer, String>, Tuple2<Integer, Integer>>();
        final Map<String, Integer> commitsPerCategory = new HashMap<String, Integer>();
        final List<ArticleEdited> articleEditeds = new ArrayList<UserInfo.ArticleEdited>();
        int numOfComments = 0;
        int numOfReverts = 0;
        int numOfUserDiscussion = 0;
        int numofSelfDiscussion = 0;

        final String userArticles = this.requester
                .getResult(this.convertRequest("action=query&format=json&list=usercontribs&ucdir=older&ucuser="
                        + userName + "&uclimit=500&ucprop=ids|sizediff|title|flags|comment|timestamp"));
        final JsonObject rootObj = this.parser.parse(userArticles).getAsJsonObject();

        final JsonArray articlesArticle = rootObj.getAsJsonObject("query").getAsJsonArray("usercontribs");
        lastUserCommits += articlesArticle.size();

        for (JsonElement elm : articlesArticle) {
            final JsonObject tmpObj = elm.getAsJsonObject();

            final Tuple2<Integer, String> key = Tuple.create(tmpObj.getAsJsonPrimitive("pageid").getAsInt(),
                    tmpObj.getAsJsonPrimitive("title").getAsString());

            if (key.getItem2().startsWith("Benutzer Diskussion:")) {
                if (key.getItem2().endsWith(userName)) {
                    numofSelfDiscussion++;
                } else {
                    numOfUserDiscussion++;
                }
            }

            final int sizediff = tmpObj.has("sizediff") ? tmpObj.getAsJsonPrimitive("sizediff").getAsInt() : 0;
            final String comment = tmpObj.has("comment") ? tmpObj.getAsJsonPrimitive("comment").getAsString()
                    : "";
            if (!comment.isEmpty()) {
                numOfComments++;
                if (this.isRevert(comment)) {
                    numOfReverts++;
                }
            }

            if (!comparableRevisions.containsKey(key)) {
                comparableRevisions.put(key, Tuple.create(0, 0));
            }
            comparableRevisions.put(key, Tuple.create(comparableRevisions.get(key).getItem1() + 1,
                    comparableRevisions.get(key).getItem2() + sizediff));
        }

        final Set<String> categorySet = new HashSet<String>();
        for (final Map.Entry<Tuple2<Integer, String>, Tuple2<Integer, Integer>> entry : comparableRevisions
                .entrySet()) {

            final String categories = this.getCategories(entry.getKey().getItem1());
            categoryEdited.add(new ArticleEdited(entry.getKey().getItem2(), entry.getValue().getItem1(),
                    entry.getValue().getItem2(), categories));

            final String[] catArr = categories.split(";");
            for (final String cat : catArr) {
                categorySet.add(cat.trim());

                if (!commitsPerCategory.containsKey(cat.trim())) {
                    commitsPerCategory.put(cat.trim(), entry.getValue().getItem1());
                } else {
                    commitsPerCategory.put(cat.trim(),
                            (commitsPerCategory.get(cat.trim()) + entry.getValue().getItem1()));
                }
            }
        }

        try {
            signInDate = this.formatter
                    .parse(user.getAsJsonPrimitive("registration").getAsString().replace('T', '_'));

        } catch (Exception e) {
            this.logger.warn(userName + " has no sign in date!");
            final String signInRsp = this.requester.getResult(
                    this.convertRequest("action=query&format=json&list=usercontribs&ucdir=newer&ucuser="
                            + userName + "&uclimit=1&ucprop=timestamp"));
            final JsonObject aa = this.parser.parse(userArticles).getAsJsonObject();
            final JsonArray aaa = aa.getAsJsonObject("query").getAsJsonArray("usercontribs");
            if (aaa.size() > 0) {
                // get the date of the first user contrib
                signInDate = this.formatter.parse(aaa.get(aaa.size() - 1).getAsJsonObject()
                        .getAsJsonPrimitive("timestamp").getAsString().replace('T', '_'));
            }
        }

        final StringBuilder categoriesStrBuilder = new StringBuilder();
        categoriesStrBuilder.append("(");
        categoriesStrBuilder.append(categorySet.size());
        categoriesStrBuilder.append(") = ");
        for (final String cat : categorySet) {
            categoriesStrBuilder.append(cat);
            categoriesStrBuilder.append("; ");
        }

        /*
         * get categories
         */
        final String categoryCommits = categoriesStrBuilder.toString().substring(0,
                categoriesStrBuilder.length() - 2);

        /*
         * get reputation
         */
        final Object[] reps = this.calcReputation(userName, lastUserCommits, blocked);
        final double reputation = (Double) reps[0];
        final String abuses = (String) reps[1];
        final int abuseCount = (Integer) reps[2];

        /*
         * user classes
         */
        String userclassNumOfCommits = "Gott";
        if (lastUserCommits < 100) {
            userclassNumOfCommits = "Rookie";
        } else if (lastUserCommits < 1000) {
            userclassNumOfCommits = "Fortgeschrittener";
        } else if (lastUserCommits < 10000) {
            userclassNumOfCommits = "Profi";
        } else if (lastUserCommits < 100000) {
            userclassNumOfCommits = "Master";
        }

        String userclassAvgCommits = "\"nicht bewertbar\"";
        double avgCommits = 0;
        if (signInDate != null) {
            avgCommits = editcount / ((System.currentTimeMillis() - signInDate.getTime()) / 86400000);
            if (avgCommits == 0.0) {
                userclassAvgCommits = "Schlafmtze";
            } else if (avgCommits < 1.0d) {
                userclassAvgCommits = "Gelegenheitssurfer";
            } else if (avgCommits < 5.0d) {
                userclassAvgCommits = "Durchschnittsuser";
            } else if (avgCommits < 15.0d) {
                userclassAvgCommits = "Vielschreiber";
            } else {
                userclassAvgCommits = "Dauergast";
            }
        }

        String userclassRevert = "\"nicht bewertbar\"";
        String userclassComment = "\"nicht bewertbar\"";

        if (lastUserCommits > 0) {
            final double revertCommitRelation = (double) numOfReverts / lastUserCommits;
            userclassRevert = "Spielverderber";
            if (revertCommitRelation < 0.01) {
                userclassRevert = "Ein-Auge-Zudrcker";
            } else if (revertCommitRelation < 0.1) {
                userclassRevert = "Gelegenheitsspieer";
            } else if (revertCommitRelation < 0.2) {
                userclassRevert = "Sturrkopf";
            } else if (revertCommitRelation < 0.5) {
                userclassRevert = "Kontrolleur";
            }

            final double commentCommitRelation = (double) numOfComments / lastUserCommits;
            userclassComment = "Saubermann";
            if (commentCommitRelation < 0.1) {
                userclassComment = "Dokuhasser";
            } else if (commentCommitRelation < 0.5) {
                userclassComment = "Ab und zu vergesslich";
            } else if (commentCommitRelation < 0.8) {
                userclassComment = "Ordnungshter";
            }
        }

        String userDiscussion = "Sehr oft";
        if (numOfUserDiscussion == 0) {
            userDiscussion = "Nie";
        } else if (numOfUserDiscussion < 3) {
            userDiscussion = "Selten";
        } else if (numOfUserDiscussion < 10) {
            userDiscussion = "Gelegentlich";
        } else if (numOfUserDiscussion < 20) {
            userDiscussion = "Oft";
        }

        String selfDiscussion = "Sehr oft";
        if (numofSelfDiscussion == 0) {
            selfDiscussion = "Nie";
        } else if (numofSelfDiscussion < 10) {
            selfDiscussion = "Selten";
        } else if (numofSelfDiscussion < 30) {
            selfDiscussion = "Gelegentlich";
        } else if (numofSelfDiscussion < 100) {
            selfDiscussion = "Oft";
        }

        return new UserInfo(userid, userName, editcount, categoryCommits, avgCommits, signInDate, reputation,
                categoryEdited, blocked, userclassNumOfCommits, userclassAvgCommits, userclassRevert,
                userclassComment, userDiscussion, selfDiscussion, commitsPerCategory, abuses, abuseCount,
                numOfReverts, numOfComments, numOfUserDiscussion, numofSelfDiscussion, isBot);
    } catch (Exception e) {
        this.logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:de.behrfried.wikianalyzer.wawebapp.server.service.JsonWikiAccess.java

License:Apache License

@Override
public CriterionInfo getCriterionInfo(List<TitleOrCategory> titlesOrCategories)
        throws CriterionNotFoundException {

    final Map<String, Map<String, Integer>> users = new HashMap<String, Map<String, Integer>>();
    final Map<String, List<Integer>> pages = new HashMap<String, List<Integer>>();
    for (final TitleOrCategory toc : titlesOrCategories) {
        if (toc.isCategory()) {
            String nextpage = "";
            do {//from   w  ww  . j a va  2  s  .com
                String resp = this.requester.getResult(this.convertRequest(
                        "action=query&format=json&list=categorymembers&cmlimit=500&cmtitle=Kategorie:"
                                + toc.getTitle() + "&cmstartsortkey=" + nextpage));

                final JsonObject root = this.parser.parse(resp).getAsJsonObject();

                final JsonArray jsonPagesArr = root.getAsJsonObject("query").getAsJsonArray("categorymembers");

                final List<Integer> pageids = new ArrayList<Integer>(jsonPagesArr.size());
                for (final JsonElement jsonElem : jsonPagesArr) {
                    pageids.add(jsonElem.getAsJsonObject().getAsJsonPrimitive("pageid").getAsInt());
                }
                pages.put(toc.getTitle(), pageids);

                nextpage = "";
                if (root.has("query-continue")) {
                    nextpage = root.getAsJsonObject("query-continue").getAsJsonObject("categorymembers")
                            .getAsJsonPrimitive("cmcontinue").getAsString();
                }

            } while (!nextpage.isEmpty());
        } else {
            final List<Integer> pageids = new ArrayList<Integer>(1);
            pageids.add(this.getPageId(toc.getTitle()));
            pages.put(toc.getTitle(), pageids);
            this.getPageId(toc.getTitle());
        }
    }

    /*
     * iterate all criterions
     */
    // User, Title, Commits
    for (final Map.Entry<String, List<Integer>> entry : pages.entrySet()) {

        for (final int pageid : entry.getValue()) {
            /*
            * iterate all revisions
            */
            int lastRev = 0;
            while (lastRev != -1) {
                final String response1 = this.requester
                        .getResult(this.convertRequest("action=query&format=json&prop=revisions&rvprop=user"
                                + "&rvlimit=500&rvdir=newer&rvexcludeuser=127.0.0.1&pageids=" + pageid
                                + "&rvstartid=" + lastRev + "&continue="));

                final JsonObject root = this.parser.parse(response1).getAsJsonObject();
                final JsonObject page = root.getAsJsonObject("query").getAsJsonObject("pages")
                        .getAsJsonObject(pageid + "");

                if (!page.has("revisions")) {
                    break;
                }

                final JsonArray jsonRevArr = page.getAsJsonArray("revisions");
                for (final JsonElement jsonElem : jsonRevArr) {
                    final String user = jsonElem.getAsJsonObject().getAsJsonPrimitive("user").getAsString();
                    if (!users.containsKey(user)) {
                        final Map<String, Integer> title = new HashMap<String, Integer>();
                        users.put(user, title);
                    }
                    final Map<String, Integer> title = users.get(user);
                    if (!title.containsKey(entry.getKey())) {
                        title.put(entry.getKey(), 0);
                    }
                    title.put(entry.getKey(), title.get(entry.getKey()) + 1);

                }

                lastRev = root.has("continue")
                        ? root.getAsJsonObject("continue").getAsJsonPrimitive("rvcontinue").getAsInt()

                        :

                        -1;
            }
        }

    }

    final List<CriterionInfo.User> userList = new ArrayList<CriterionInfo.User>(users.size());
    outer: for (final Map.Entry<String, Map<String, Integer>> entry : users.entrySet()) {

        final CriterionInfo.User user = new CriterionInfo.User(entry.getKey(), 1);
        for (final TitleOrCategory toc : titlesOrCategories) {
            if (!entry.getValue().containsKey(toc.getTitle())) {
                continue outer;
            }
            user.setMatch(user.getMatch() * entry.getValue().get(toc.getTitle()));
        }
        userList.add(user);
    }
    outer: for (int i = 0; i < userList.size(); i++) {
        final CriterionInfo.User us = userList.get(i);
        final String userBotRsp = this.requester.getResult(this.convertRequest(
                "action=query&format=json&list=users&usprop=groups|blockinfo&ususers=" + us.getUserName()));
        final JsonObject usersJsonObj = this.parser.parse(userBotRsp).getAsJsonObject().getAsJsonObject("query")
                .getAsJsonArray("users").get(0).getAsJsonObject();
        if (usersJsonObj.has("blockid")) {
            userList.remove(i);
            continue;
        }
        if (!usersJsonObj.has("groups")) {
            userList.remove(i);
            continue;
        }
        final JsonArray groupsJsonArr = usersJsonObj.getAsJsonArray("groups");
        for (JsonElement jsonElement : groupsJsonArr) {
            if ("bot".equals(jsonElement.getAsJsonPrimitive().getAsString())) {
                userList.remove(i);
                continue outer;
            }
        }
        us.setMatch(us.getMatch()
                * (Double) this.calcReputation(us.getUserName(), users.get(us.getUserName()).size(), false)[0]);
    }
    Collections.sort(userList, new Comparator<CriterionInfo.User>() {
        @Override
        public int compare(CriterionInfo.User user, CriterionInfo.User user2) {
            return (int) Math.signum(user2.getMatch() - user.getMatch());
        }
    });

    return new CriterionInfo(userList);
}

From source file:de.elomagic.carafile.share.DateDeserializer.java

License:Apache License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    return new Date(json.getAsJsonPrimitive().getAsLong());
}

From source file:de.sub.goobi.helper.HelperSchritte.java

License:Open Source License

private void replaceJsonElement(JsonElement jel, VariableReplacer replacer) {
    if (jel.isJsonObject()) {
        JsonObject obj = jel.getAsJsonObject();
        for (Entry<String, JsonElement> objEntry : obj.entrySet()) {
            if (objEntry.getValue().isJsonPrimitive()) {
                JsonPrimitive jPrim = objEntry.getValue().getAsJsonPrimitive();
                if (jPrim.isString()) {
                    String newVal = replacer.replace(jPrim.getAsString());
                    obj.addProperty(objEntry.getKey(), newVal);
                }/*w w  w  . j a  va2  s . c  o  m*/
            } else {
                replaceJsonElement(objEntry.getValue(), replacer);
            }
        }
    } else if (jel.isJsonArray()) {
        JsonArray jArr = jel.getAsJsonArray();
        for (int i = 0; i < jArr.size(); i++) {
            JsonElement innerJel = jArr.get(i);
            if (innerJel.isJsonPrimitive()) {
                JsonPrimitive jPrim = innerJel.getAsJsonPrimitive();
                if (jPrim.isString()) {
                    String newVal = replacer.replace(jPrim.getAsString());
                    jArr.set(i, new JsonPrimitive(newVal));
                }
            } else {
                replaceJsonElement(innerJel, replacer);
            }
        }
    }

}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    if (baseClass.isAssignableFrom(type.getRawType())) {
        return new TypeAdapter<T>() {
            @Override//from www  . j  av  a2 s  . com
            public void write(JsonWriter out, T value) throws IOException {
                if (value == null) {
                    out.nullValue();
                    return;
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter delegate = delegateFactory.create(gson, TypeToken.get(value.getClass()));
                JsonTreeWriter treeWriter = new JsonTreeWriter();
                delegate.write(treeWriter, value);
                JsonElement el = treeWriter.get();

                if (el.isJsonObject()) {
                    JsonObject elObject = el.getAsJsonObject();
                    elObject.addProperty(RuntimeTypeAdapterFactory.TYPE, value.getClass().getName());
                    Streams.write(elObject, out);
                } else {
                    Streams.write(el, out);
                }
            }

            @Override
            public T read(JsonReader in) throws IOException {
                // TODO: need to handle null
                JsonElement el = Streams.parse(in);
                Class<? extends T> runtimeType = getRuntimeType(el, type);
                if (runtimeType == null) {
                    throw new ParseException("RuntimeTypeAdapter: Unable to parse runtime type.");
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter<? extends T> delegate = delegateFactory.create(gson,
                        TypeToken.get(runtimeType));

                if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
                    JsonObject typeObject = new JsonObject();
                    typeObject.addProperty(TYPE, el.getAsString());
                    el = typeObject;
                }

                return delegate.read(new JsonTreeReader(el));
            }

        };
    }
    return null;
}

From source file:edu.mit.media.funf.json.JsonUtils.java

License:Open Source License

/**
 * Return an immutable JsonElement.  Either IJsonObject, IJsonArray, or other immutable JsonPrimitive.
 * @param el//from w ww .  j  av  a  2  s. c  o  m
 * @return
 */
public static JsonElement immutable(JsonElement el) {
    if (el instanceof JsonObject) {
        return new IJsonObject(el.getAsJsonObject());
    } else if (el instanceof JsonArray) {
        return new IJsonArray(el.getAsJsonArray());
    } else if (el instanceof JsonPrimitive && el.getAsJsonPrimitive().isNumber()) {
        // Ensure that all LazilyParsedNumbers have been parsed into a consistent Number type.
        // Otherwise hash codes are not consistent, because LazilyParsedNumbers are never seen as integral.
        return new JsonPrimitive(el.getAsBigDecimal());
    }
    return el;
}

From source file:edu.wustl.lookingglass.community.api.DateDeserializer.java

License:Open Source License

@Override
public org.joda.time.DateTime deserialize(com.google.gson.JsonElement json, java.lang.reflect.Type typeOfT,
        com.google.gson.JsonDeserializationContext context) throws com.google.gson.JsonParseException {
    org.joda.time.format.DateTimeFormatter parser = org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis();
    return parser.parseDateTime(json.getAsJsonPrimitive().getAsString());
}

From source file:edu.wustl.lookingglass.community.api.UUIDDeserializer.java

License:Open Source License

@Override
public java.util.UUID deserialize(com.google.gson.JsonElement json, java.lang.reflect.Type typeOfT,
        com.google.gson.JsonDeserializationContext context) throws com.google.gson.JsonParseException {
    try {//from  w  w  w  .  j ava 2s .  c  o  m
        return java.util.UUID.fromString(json.getAsJsonPrimitive().getAsString());
    } catch (IllegalArgumentException e) {
        throw new com.google.gson.JsonParseException(e.getMessage());
    }
}