Example usage for com.fasterxml.jackson.core JsonParser setCodec

List of usage examples for com.fasterxml.jackson.core JsonParser setCodec

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonParser setCodec.

Prototype

public abstract void setCodec(ObjectCodec c);

Source Link

Document

Setter that allows defining ObjectCodec associated with this parser, if any.

Usage

From source file:org.apache.airavata.db.AbstractThriftDeserializer.java

@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final T instance = newInstance();
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode rootNode = mapper.readTree(jp);
    final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields();

    while (iterator.hasNext()) {
        final Map.Entry<String, JsonNode> currentField = iterator.next();
        try {//w  w w. j a v a 2  s .  com
            /*
             * If the current node is not a null value, process it.  Otherwise,
             * skip it.  Jackson will treat the null as a 0 for primitive
             * number types, which in turn will make Thrift think the field
             * has been set. Also we ignore the MongoDB specific _id field
             */
            if (!currentField.getKey().equalsIgnoreCase("_id")
                    && currentField.getValue().getNodeType() != JsonNodeType.NULL) {
                final E field = getField(
                        CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey()));
                final JsonParser parser = currentField.getValue().traverse();
                parser.setCodec(mapper);
                final Object value = mapper.readValue(parser, generateValueType(instance, field));
                if (value != null) {
                    log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(),
                            value, value.getClass().getName()));
                    instance.setFieldValue(field, value);
                } else {
                    log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
                }
            } else {
                log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
            }
        } catch (final NoSuchFieldException | IllegalArgumentException e) {
            log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e);
            ctxt.mappingException(e.getMessage());
        }
    }

    try {
        // Validate that the instance contains all required fields.
        validate(instance);
    } catch (final TException e) {
        log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(),
                instance.getClass().getName(), e));
        ctxt.mappingException(e.getMessage());
    }

    return instance;
}

From source file:org.springframework.social.facebook.api.impl.json.CommentListAndCountDeserializer.java

@SuppressWarnings("unchecked")
@Override//from  www.  j  av a2s.c  o m
public ListAndCount<Comment> deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode commentsNode = jp.readValueAs(JsonNode.class);
        JsonNode dataNode = commentsNode.get("data");
        List<Comment> commentsList = dataNode != null
                ? (List<Comment>) mapper.reader(new TypeReference<List<Comment>>() {
                }).readValue(dataNode)
                : Collections.<Comment>emptyList();
        JsonNode countNode = commentsNode.get("count");
        int commentCount = countNode != null ? countNode.intValue() : 0;
        return new ListAndCount<Comment>(commentsList, commentCount);
    }

    return null;
}

From source file:org.springframework.social.facebook.api.impl.json.ReferenceListAndCountDeserializer.java

@SuppressWarnings("unchecked")
@Override/* w ww .  j a  v a  2 s . co  m*/
public ListAndCount<Reference> deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode node = jp.readValueAs(JsonNode.class);
        JsonNode dataNode = node.get("data");
        List<Reference> commentsList = dataNode != null
                ? (List<Reference>) mapper.reader(new TypeReference<List<Reference>>() {
                }).readValue(dataNode)
                : Collections.<Reference>emptyList();
        JsonNode countNode = node.get("count");
        int referenceCount = countNode != null ? countNode.intValue() : 0;
        return new ListAndCount<Reference>(commentsList, referenceCount);
    }

    return null;
}

From source file:com.github.fge.jsonpatch.mergepatch.JsonMergePatchDeserializer.java

@Override
public JsonMergePatch deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    // FIXME: see comment above
    jp.setCodec(CODEC);
    final JsonNode node = jp.readValueAsTree();

    /*/*from w w  w  .  j a v  a  2  s.c om*/
     * Not an object: the simple case
     */
    if (!node.isObject())
        return new NonObjectMergePatch(node);

    /*
     * The complicated case...
     *
     * We have to build a set of removed members, plus a map of modified
     * members.
     */

    final Set<String> removedMembers = Sets.newHashSet();
    final Map<String, JsonMergePatch> modifiedMembers = Maps.newHashMap();
    final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();

    Map.Entry<String, JsonNode> entry;

    while (iterator.hasNext()) {
        entry = iterator.next();
        if (entry.getValue().isNull())
            removedMembers.add(entry.getKey());
        else {
            final JsonMergePatch value = deserialize(entry.getValue().traverse(), ctxt);
            modifiedMembers.put(entry.getKey(), value);
        }
    }

    return new ObjectMergePatch(removedMembers, modifiedMembers);
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONEntryDeserializer.java

private String setInline(final String name, final String suffix, final ObjectNode tree, final ObjectCodec codec,
        final JSONLink link) throws IOException {

    final String entryNamePrefix = name.substring(0, name.indexOf(suffix));
    if (tree.has(entryNamePrefix)) {
        final JsonNode inline = tree.path(entryNamePrefix);

        if (inline instanceof ObjectNode) {
            final JsonParser inlineParser = inline.traverse();
            inlineParser.setCodec(codec);
            link.setInlineEntry(inlineParser.readValuesAs(JSONEntry.class).next());
        }/*from  w  ww.  j  a  v  a2  s. c  o  m*/

        if (inline instanceof ArrayNode) {
            final JSONFeed feed = new JSONFeed();
            final Iterator<JsonNode> entries = ((ArrayNode) inline).elements();
            while (entries.hasNext()) {
                final JsonParser inlineParser = entries.next().traverse();
                inlineParser.setCodec(codec);
                feed.addEntry(inlineParser.readValuesAs(JSONEntry.class).next());
            }

            link.setInlineFeed(feed);
        }
    }
    return entryNamePrefix;
}

From source file:org.agorava.linkedin.jackson.LinkedInNetworkUpdateListDeserializer.java

@Override
public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = BeanResolver.getInstance().resolve(ObjectMapper.class);
    jp.setCodec(mapper);

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);/*from w w  w  .j a  v a2s  . com*/

        UpdateContent updatedContent = null;
        UpdateType type = linkedInNetworkUpdate.getUpdateType();
        JsonNode updatedNode = dataNode.get("updateContent");
        JsonNode person = updatedNode.get("person");
        if (type == UpdateType.MSFC) {
            // Totally different.  Looks like a bad API to be honest.
            person = updatedNode.get("companyPersonUpdate").get("person");
        }

        switch (type) {
        case CONN:
            updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() {
            }).readValue(person);
            break;
        case STAT:
            updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() {
            }).readValue(person);
            break;
        case JGRP:
            updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() {
            }).readValue(person);
            break;
        case PREC:
        case SVPR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() {
            }).readValue(person);
            break;
        case APPM:
            updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() {
            }).readValue(person);
            break;
        case MSFC:
            updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() {
            }).readValue(person);
            break;
        case VIRL:
            updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() {
            }).readValue(person);
            break;
        case SHAR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() {
            }).readValue(person);
            break;
        case CMPY:
            updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() {
            }).readValue(updatedNode);
            break;
        default:
            try {
                updatedContent = mapper.reader(new TypeReference<UpdateContent>() {
                }).readValue(person);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // Need to use reflection to set private updateContent field
        try {
            Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent");
            f.setAccessible(true);
            f.set(linkedInNetworkUpdate, updatedContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type == UpdateType.MSFC) {
            // Set the action via reflection as it's private
            String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText();
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updatedContent, action);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set following via reflection as it's private
            Company company = mapper.reader(new TypeReference<Company>() {
            }).readValue(updatedNode.get("company"));
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("following");
                f.setAccessible(true);
                f.set(updatedContent, company);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == UpdateType.VIRL) {
            JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate");
            UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() {
            }).readValue(originalUpdate);
            String code = updatedNode.path("updateAction").path("action").path("code").textValue();

            // Set private immutable field action on updateAction
            try {
                Field f = UpdateAction.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updateAction, code);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set private immutable field  updateAction on updatedContent
            try {
                Field f = UpdateContentViral.class.getDeclaredField("updateAction");
                f.setAccessible(true);
                f.set(updatedContent, updateAction);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return linkedInNetworkUpdate;
    }

    return null;
}

From source file:org.springframework.social.linkedin.api.impl.json.LinkedInNetworkUpdateListDeserializer.java

@Override
public LinkedInNetworkUpdate deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new LinkedInModule());
    jp.setCodec(mapper);

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);//from w  w w. j  av a 2 s  . c o  m

        UpdateContent updatedContent = null;
        UpdateType type = linkedInNetworkUpdate.getUpdateType();
        JsonNode updatedNode = dataNode.get("updateContent");
        JsonNode person = updatedNode.get("person");
        if (type == UpdateType.MSFC) {
            // Totally different.  Looks like a bad API to be honest.
            person = updatedNode.get("companyPersonUpdate").get("person");
        }

        switch (type) {
        case CONN:
            updatedContent = mapper.reader(new TypeReference<UpdateContentConnection>() {
            }).readValue(person);
            break;
        case STAT:
            updatedContent = mapper.reader(new TypeReference<UpdateContentStatus>() {
            }).readValue(person);
            break;
        case JGRP:
            updatedContent = mapper.reader(new TypeReference<UpdateContentGroup>() {
            }).readValue(person);
            break;
        case PREC:
        case SVPR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentRecommendation>() {
            }).readValue(person);
            break;
        case APPM:
            updatedContent = mapper.reader(new TypeReference<UpdateContentPersonActivity>() {
            }).readValue(person);
            break;
        case MSFC:
            updatedContent = mapper.reader(new TypeReference<UpdateContentFollow>() {
            }).readValue(person);
            break;
        case VIRL:
            updatedContent = mapper.reader(new TypeReference<UpdateContentViral>() {
            }).readValue(person);
            break;
        case SHAR:
            updatedContent = mapper.reader(new TypeReference<UpdateContentShare>() {
            }).readValue(person);
            break;
        case CMPY:
            updatedContent = mapper.reader(new TypeReference<UpdateContentCompany>() {
            }).readValue(updatedNode);
            break;
        default:
            try {
                updatedContent = mapper.reader(new TypeReference<UpdateContent>() {
                }).readValue(person);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // Need to use reflection to set private updateContent field
        try {
            Field f = LinkedInNetworkUpdate.class.getDeclaredField("updateContent");
            f.setAccessible(true);
            f.set(linkedInNetworkUpdate, updatedContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (type == UpdateType.MSFC) {
            // Set the action via reflection as it's private
            String action = updatedNode.get("companyPersonUpdate").get("action").get("code").asText();
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updatedContent, action);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set following via reflection as it's private
            Company company = mapper.reader(new TypeReference<Company>() {
            }).readValue(updatedNode.get("company"));
            try {
                Field f = UpdateContentFollow.class.getDeclaredField("following");
                f.setAccessible(true);
                f.set(updatedContent, company);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else if (type == UpdateType.VIRL) {
            JsonNode originalUpdate = updatedNode.path("updateAction").path("originalUpdate");
            UpdateAction updateAction = mapper.reader(new TypeReference<UpdateAction>() {
            }).readValue(originalUpdate);
            String code = updatedNode.path("updateAction").path("action").path("code").textValue();

            // Set private immutable field action on updateAction
            try {
                Field f = UpdateAction.class.getDeclaredField("action");
                f.setAccessible(true);
                f.set(updateAction, code);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // Set private immutable field  updateAction on updatedContent
            try {
                Field f = UpdateContentViral.class.getDeclaredField("updateAction");
                f.setAccessible(true);
                f.set(updatedContent, updateAction);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return linkedInNetworkUpdate;
    }

    return null;
}

From source file:com.evolveum.midpoint.prism.lex.json.AbstractJsonLexicalProcessor.java

private JsonParser configureParser(JsonParser parser) {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule sm = new SimpleModule();
    sm.addDeserializer(QName.class, new QNameDeserializer());
    sm.addDeserializer(ItemPath.class, new ItemPathDeserializer());
    sm.addDeserializer(PolyString.class, new PolyStringDeserializer());
    sm.addDeserializer(ItemPathType.class, new ItemPathTypeDeserializer());

    mapper.registerModule(sm);//from   w w w . ja va  2  s. co m
    parser.setCodec(mapper);
    return parser;
}

From source file:org.springframework.social.weibo.api.impl.json.TrendsDeserializer.java

@Override
public SortedSet<Trends> deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    TreeSet<Trends> result = new TreeSet<Trends>(comparator);
    TreeNode treeNode = jp.readValueAsTree();

    Iterator<String> fieldNames = treeNode.fieldNames();

    while (fieldNames.hasNext()) {
        Trends trends = new Trends();
        try {/*from w  w  w. ja  v  a  2 s.c o  m*/
            String filedName = fieldNames.next();
            dateFormat.applyPattern(retrieveDateFormatPattern(filedName));
            trends.setDate(dateFormat.parse(filedName));
            TreeNode trendsNode = treeNode.get(filedName);
            if (trendsNode.isArray()) {
                for (int i = 0; i < trendsNode.size(); i++) {
                    JsonParser nodeParser = trendsNode.get(i).traverse();
                    nodeParser.setCodec(jp.getCodec());
                    Trend readValueAs = nodeParser.readValueAs(Trend.class);
                    trends.getTrends().add(readValueAs);
                }
            }
            result.add(trends);
        } catch (ParseException e) {
            logger.warn("Unable to parse date", e);
        }
    }

    return result;
}