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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content into a Java type, reference to which is passed as argument.

Usage

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);/*from  ww  w.  j  a v a 2 s  .  c o  m*/

    JsonNode dataNode = jp.readValueAs(JsonNode.class);
    if (dataNode != null) {
        LinkedInNetworkUpdate linkedInNetworkUpdate = (LinkedInNetworkUpdate) mapper
                .reader(new TypeReference<LinkedInNetworkUpdate>() {
                }).readValue(dataNode);

        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.apache.ode.jacob.soup.jackson.ChannelRefDeserializer.java

@Override
public ChannelRef deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    Object target = null;//from  w  w  w .jav a  2  s  .c  o  m

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String fieldname = jp.getCurrentName();
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
            // if we're not already on the field, advance by one.
            jp.nextToken();
        }

        if ("target".equals(fieldname)) {
            target = jp.readValueAs(Object.class);
        }
    }

    if (target == null) {
        throw ctxt.mappingException(ChannelRef.class);
    }

    return new ChannelRef(target);
}

From source file:com.netflix.discovery.converters.jackson.serializer.ApplicationXmlDeserializer.java

@Override
public Application deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    String name = null;//  www  .  j  a v a 2s. c  om
    List<InstanceInfo> instances = new ArrayList<>();
    while (jp.nextToken() == JsonToken.FIELD_NAME) {
        String fieldName = jp.getCurrentName();
        jp.nextToken(); // to point to value
        if ("name".equals(fieldName)) {
            name = jp.getValueAsString();
        } else if ("instance".equals(fieldName)) {
            instances.add(jp.readValueAs(InstanceInfo.class));
        } else {
            throw new JsonMappingException("Unexpected field " + fieldName, jp.getCurrentLocation());
        }
    }
    return new Application(name, instances);
}

From source file:com.basistech.rosette.dm.jackson.array.MorphoAnalysisListArrayDeserializer.java

@Override
public List<MorphoAnalysis> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (jp.getCurrentToken() != JsonToken.START_ARRAY) {
        throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "Expected array of items");
    }/*from   w ww.  j  a  v a 2  s  .  c om*/
    List<MorphoAnalysis> results = Lists.newArrayList();
    MorphoAnalysisTypes type = MorphoAnalysisTypes.PLAIN;
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        if (jp.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
            type = MorphoAnalysisTypes.byOrdinal(jp.getIntValue());
            jp.nextToken();
        }
        results.add(jp.readValueAs(type.getMorphoAnalysisClass()));
    }
    return ImmutableList.copyOf(results);
}

From source file:ch.rasc.wampspring.message.CallMessage.java

public CallMessage(JsonParser jp, WampSession wampSession) throws IOException {
    super(WampMessageType.CALL);

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }/*w w w.ja  va 2s . c o m*/
    this.callID = jp.getValueAsString();

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }
    this.procURI = replacePrefix(jp.getValueAsString(), wampSession);

    List<Object> args = new ArrayList<>();
    while (jp.nextToken() != JsonToken.END_ARRAY) {
        args.add(jp.readValueAs(Object.class));
    }

    if (!args.isEmpty()) {
        this.arguments = Collections.unmodifiableList(args);
    } else {
        this.arguments = null;
    }
}

From source file:org.apache.taverna.scufl2.api.io.structure.StructureReader.java

protected void parseLine(final String nextLine) throws ReaderException {
    try (Scanner scanner = new Scanner(nextLine.trim())) {
        // In case it is the last line
        if (!scanner.hasNext())
            return;
        // allow any whitespace
        String next = scanner.next();

        if (next.isEmpty())
            return;
        switch (next) {
        case "WorkflowBundle":
            parseWorkflowBundle(scanner);
            return;
        case "MainWorkflow":
            mainWorkflow = parseName(scanner);
            return;
        case "Workflow":
            parseWorkflow(scanner);//from  w ww.ja  v a  2  s  .c o  m
            return;
        case "In":
        case "Out":
            parsePort(scanner, next);
            return;
        case "Links":
            level = Level.Links;
            processor = null;
            return;
        case "Controls":
            level = Level.Controls;
            return;
        case "MainProfile":
            mainProfile = parseName(scanner);
            return;
        case "Profile":
            parseProfile(scanner);
            return;
        case "Type":
            parseType(nextLine);
            return;
        case "ProcessorBinding":
            parseProcessorBinding(scanner);
            return;
        case "InputPortBindings":
            level = Level.InputPortBindings;
            return;
        case "OutputPortBindings":
            level = Level.OutputPortBindings;
            return;
        case "Configuration":
            parseConfiguration(scanner);
            return;
        case "Configures":
            parseConfigures(scanner);
            return;
        case "Activity":
            switch (level) {
            case Profile:
            case Activity:
                level = Level.Activity;
                activity = new Activity();
                activity.setName(parseName(scanner));
                profile.getActivities().add(activity);
                return;
            case ProcessorBinding:
                Activity boundActivity = profile.getActivities().getByName(parseName(scanner));
                processorBinding.setBoundActivity(boundActivity);
                return;
            default:
                break;
            }
            break;
        case "Processor":
            switch (level) {
            case Workflow:
            case Processor:
                level = Level.Processor;
                processor = new Processor();
                processor.setName(parseName(scanner));
                processor.setParent(workflow);
                workflow.getProcessors().add(processor);
                return;
            case ProcessorBinding:
                String[] wfProcName = parseName(scanner).split(":");
                Workflow wf = wb.getWorkflows().getByName(wfProcName[0]);
                Processor boundProcessor = wf.getProcessors().getByName(wfProcName[1]);
                processorBinding.setBoundProcessor(boundProcessor);
                return;
            default:
                break;
            }
            break;
        }

        if (next.equals("block")) {
            Matcher blockMatcher = blockPattern.matcher(nextLine);
            blockMatcher.find();
            String block = blockMatcher.group(1);
            String untilFinish = blockMatcher.group(2);

            Processor blockProc = workflow.getProcessors().getByName(block);
            Processor untilFinishedProc = workflow.getProcessors().getByName(untilFinish);
            new BlockingControlLink(blockProc, untilFinishedProc);
        }
        if (next.startsWith("'") && level.equals(Level.Links)) {
            Matcher linkMatcher = linkPattern.matcher(nextLine);
            linkMatcher.find();
            String firstLink = linkMatcher.group(1);
            String secondLink = linkMatcher.group(2);

            SenderPort senderPort;
            if (firstLink.contains(":")) {
                String[] procPort = firstLink.split(":");
                Processor proc = workflow.getProcessors().getByName(procPort[0]);
                senderPort = proc.getOutputPorts().getByName(procPort[1]);
            } else
                senderPort = workflow.getInputPorts().getByName(firstLink);

            ReceiverPort receiverPort;
            if (secondLink.contains(":")) {
                String[] procPort = secondLink.split(":");
                Processor proc = workflow.getProcessors().getByName(procPort[0]);
                receiverPort = proc.getInputPorts().getByName(procPort[1]);
            } else
                receiverPort = workflow.getOutputPorts().getByName(secondLink);

            new DataLink(workflow, senderPort, receiverPort);
            return;
        }

        if (next.startsWith("'") && (level == Level.InputPortBindings || level == Level.OutputPortBindings)) {
            Matcher linkMatcher = linkPattern.matcher(nextLine);
            linkMatcher.find();
            String firstLink = linkMatcher.group(1);
            String secondLink = linkMatcher.group(2);
            if (level == Level.InputPortBindings) {
                InputProcessorPort processorPort = processorBinding.getBoundProcessor().getInputPorts()
                        .getByName(firstLink);
                InputActivityPort activityPort = processorBinding.getBoundActivity().getInputPorts()
                        .getByName(secondLink);
                new ProcessorInputPortBinding(processorBinding, processorPort, activityPort);
            } else {
                OutputActivityPort activityPort = processorBinding.getBoundActivity().getOutputPorts()
                        .getByName(firstLink);
                OutputProcessorPort processorPort = processorBinding.getBoundProcessor().getOutputPorts()
                        .getByName(secondLink);
                new ProcessorOutputPortBinding(processorBinding, activityPort, processorPort);
            }
            return;
        }
        if (level == Level.JSON) {
            /*
             * A silly reader that feeds (no more than) a single line at a
             * time from our parent scanner, starting with the current line
             */
            Reader reader = new Reader() {
                char[] line = nextLine.toCharArray();
                int pos = 0;

                @Override
                public int read(char[] cbuf, int off, int len) throws IOException {
                    if (pos >= line.length) {
                        // Need to read next line to fill buffer
                        if (!StructureReader.this.scanner.hasNextLine())
                            return -1;
                        String newLine = StructureReader.this.scanner.nextLine();
                        pos = 0;
                        line = newLine.toCharArray();
                        // System.out.println("Read new line: " + newLine);
                    }
                    int length = Math.min(len, line.length - pos);
                    if (length <= 0)
                        return 0;
                    arraycopy(line, pos, cbuf, off, length);
                    pos += length;
                    return length;
                }

                @Override
                public void close() throws IOException {
                    line = null;
                }
            };

            ObjectMapper mapper = new ObjectMapper();
            try {
                JsonParser parser = mapper.getFactory().createParser(reader);
                JsonNode jsonNode = parser.readValueAs(JsonNode.class);
                // System.out.println("Parsed " + jsonNode);
                configuration.setJson(jsonNode);
            } catch (IOException e) {
                throw new ReaderException("Can't parse json", e);
            }
            level = Level.Configuration;
            return;
        }
    }
}

From source file:com.kaaprotech.satu.jackson.SatuDeserializers.java

@Override
public JsonDeserializer<?> findCollectionDeserializer(final CollectionType type,
        final DeserializationConfig config, final BeanDescription beanDesc,
        final TypeDeserializer elementTypeDeserializer, final JsonDeserializer<?> elementDeserializer)
        throws JsonMappingException {

    if (ImmutableSet.class.isAssignableFrom(type.getRawClass())) {
        return new StdDeserializer<Object>(type) {
            private static final long serialVersionUID = 1L;

            @Override/*from   w  w  w.j  a  va  2 s. c  o  m*/
            public Object deserialize(JsonParser jp, DeserializationContext context) throws IOException {

                if (jp.isExpectedStartArrayToken()) {
                    JsonToken t;

                    MutableSet<Object> s = Sets.mutable.of();

                    while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
                        Object value;
                        if (t == JsonToken.VALUE_NULL) {
                            value = null;
                        } else if (elementDeserializer == null) {
                            value = jp.readValueAs(type.getContentType().getRawClass());
                        } else if (elementTypeDeserializer == null) {
                            value = elementDeserializer.deserialize(jp, context);
                        } else {
                            value = elementDeserializer.deserializeWithType(jp, context,
                                    elementTypeDeserializer);
                        }
                        s.add(value);
                    }
                    return s.toImmutable();
                }
                throw context.mappingException(type.getRawClass());
            }
        };
    }

    return super.findCollectionDeserializer(type, config, beanDesc, elementTypeDeserializer,
            elementDeserializer);
}

From source file:ch.rasc.wampspring.message.CallErrorMessage.java

public CallErrorMessage(JsonParser jp) throws IOException {
    super(WampMessageType.CALLERROR);

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }//from w  w w .  j  a  v  a2s  .c o  m
    this.callID = jp.getValueAsString();

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }
    this.errorURI = jp.getValueAsString();

    if (jp.nextToken() != JsonToken.VALUE_STRING) {
        throw new IOException();
    }
    this.errorDesc = jp.getValueAsString();

    if (jp.nextToken() != JsonToken.END_ARRAY) {
        this.errorDetails = jp.readValueAs(Object.class);
    } else {
        this.errorDetails = null;
    }
}

From source file:tachyon.master.MasterInfoIntegrationTest.java

@Test
public void writeImageTest() throws IOException {
    // initialize the MasterInfo
    Journal journal = new Journal(mLocalTachyonCluster.getTachyonHome() + "journal/", "image.data", "log.data",
            mMasterTachyonConf);/*from w w w  .  ja v  a 2  s .c  om*/
    MasterInfo info = new MasterInfo(new InetSocketAddress(9999), journal, mExecutorService,
            mMasterTachyonConf);

    // create the output streams
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    ObjectMapper mapper = JsonObject.createObjectMapper();
    ObjectWriter writer = mapper.writer();
    ImageElement version = null;
    ImageElement checkpoint = null;

    // write the image
    info.writeImage(writer, dos);

    // parse the written bytes and look for the Checkpoint and Version ImageElements
    String[] splits = new String(os.toByteArray()).split("\n");
    for (String split : splits) {
        byte[] bytes = split.getBytes();
        JsonParser parser = mapper.getFactory().createParser(bytes);
        ImageElement ele = parser.readValueAs(ImageElement.class);

        if (ele.mType.equals(ImageElementType.Checkpoint)) {
            checkpoint = ele;
        }

        if (ele.mType.equals(ImageElementType.Version)) {
            version = ele;
        }
    }

    // test the elements
    Assert.assertNotNull(checkpoint);
    Assert.assertEquals(checkpoint.mType, ImageElementType.Checkpoint);
    Assert.assertEquals(Constants.JOURNAL_VERSION, version.getInt("version").intValue());
    Assert.assertEquals(1, checkpoint.getInt("inodeCounter").intValue());
    Assert.assertEquals(0, checkpoint.getInt("editTransactionCounter").intValue());
    Assert.assertEquals(0, checkpoint.getInt("dependencyCounter").intValue());
}

From source file:eu.trentorise.opendata.semtext.jackson.MetadataDeserializer.java

@Override
public Map<String, Object> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {

    ImmutableMap.Builder<String, Object> retb = ImmutableMap.builder();

    while (jp.nextToken() != JsonToken.END_OBJECT) {

        String namespace = jp.getCurrentName();
        // current token is "name",
        // move to next, which is "name"'s value
        jp.nextToken();/*from  w  w  w  .  j  ava  2 s. c  o m*/

        ImmutableSet<String> namespaces = SemTextModule.getMetadataNamespaces(hasMetadataClass);
        if (namespaces.contains(namespace)) {
            TypeReference typeRef = SemTextModule.getMetadataTypeReference(hasMetadataClass, namespace);

            Object metadata;

            try {
                metadata = jp.readValueAs(typeRef);
            } catch (Exception ex) {
                throw new SemTextMetadataException("Jackson error while deserializing metadata - ",
                        hasMetadataClass, namespace, typeRef, ex);
            }

            if (metadata == null) {
                throw new SemTextMetadataException("Found null metadata while deserializing!", hasMetadataClass,
                        namespace, typeRef);
            }

            retb.put(namespace, metadata);
        } else {
            throw new SemTextMetadataException(
                    "Found metadata under not registered namespace while deserializing!", hasMetadataClass,
                    namespace, null);
        }
    }

    return retb.build();
}