Example usage for com.fasterxml.jackson.databind ObjectMapper readTree

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readTree.

Prototype

public JsonNode readTree(URL source) throws IOException, JsonProcessingException 

Source Link

Document

Method to deserialize JSON content as tree expressed using set of JsonNode instances.

Usage

From source file:com.clicktravel.infrastructure.messaging.aws.sqs.SqsTypedMessageQueue.java

@Override
protected TypedMessage toMessage(final com.amazonaws.services.sqs.model.Message sqsMessage) {
    final String receiptHandle = sqsMessage.getReceiptHandle();
    final String messageId = sqsMessage.getMessageId();
    try {/*from  w ww  . ja  va 2 s . c o m*/
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode jsonNode = mapper.readTree(sqsMessage.getBody());
        final String messageType = jsonNode.get("Subject").textValue();
        final String messagePayload = jsonNode.get("Message").textValue();
        return new SimpleMessage(messageType, messagePayload, messageId, receiptHandle);
    } catch (final Exception e) {
        return new InvalidTypedMessage(messageId, receiptHandle,
                new MessageParseException("Could not parse message from SQS message: " + sqsMessage.getBody()));
    }
}

From source file:com.dhenton9000.jersey.client.JerseyClientExplorer.java

public void doSimpleExample() throws IOException {

    ClientConfig config = new ClientConfig();
    Client client = ClientBuilder.newClient(config);
    WebTarget target = client.target(getBaseURI());

    Response response = target.path("restaurant").path("4").request().accept(MediaType.APPLICATION_JSON)
            .get(Response.class);

    if (response.getStatus() != 200) {
        LOG.error("status problem for request");
    } else {/* w  ww .ja  v  a  2s  . c om*/
        LOG.debug("response " + response.getEntity().getClass().getName());
    }
    String res = response.readEntity(String.class);
    LOG.debug(res);

    ObjectMapper myreader = new ObjectMapper();

    JsonNode restaurantObject = myreader.readTree(res);
    LOG.debug(restaurantObject.get("name"));

    Restaurant r = myreader.readValue(res, Restaurant.class);

    LOG.debug(r.getReviewCollection().size());

}

From source file:com.evrythng.java.wrapper.mapping.BatchPopulatingTaskOutputParametersDeserializer.java

@Override
public BatchPopulatingTask.OutputParameters deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode typeNode = node.get(BatchPopulatingTask.OutputParameters.FIELD_TYPE);
    if (typeNode == null) {
        throw new JsonMappingException(
                "Cannot deserialize adi generation output parameters without type field");
    }/*from  w w w  .  j av a  2s.  com*/
    String typeRaw = getFieldValue(typeNode);
    Class<? extends BatchPopulatingTask.OutputParameters> subtypeClass = classForType(
            BatchPopulatingTask.OutputParameters.Type.valueOf(typeRaw.toUpperCase()));
    return mapper.readValue(node.toString(), subtypeClass);
}

From source file:com.evrythng.java.wrapper.mapping.GeoJsonDeserializerImpl.java

@Override
public GeoJson deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectCodec codec = jp.getCodec();/*from   w  ww.  j a  va2  s .  c  om*/
    ObjectMapper mapper = (ObjectMapper) codec;
    ObjectNode root = (ObjectNode) mapper.readTree(jp);
    JsonNode type = root.get(getTypeFieldName());
    if (type == null) {
        throw new IllegalArgumentException(this.getValueClass().getSimpleName() + " type cannot be empty.");
    }
    String sType = type.textValue();
    if (sType == null || sType.isEmpty()) {
        throw new IllegalArgumentException(this.getValueClass().getSimpleName() + " type cannot be empty.");
    }

    Class<GeoJson> clazz = (Class<GeoJson>) resolveClass(sType);

    GeoJson obj = codec.treeToValue(root, clazz);
    if (obj == null) {
        throw new IllegalArgumentException(
                this.getValueClass().getSimpleName() + " type deserialised as null: " + root.toString());
    }
    return obj;
}

From source file:jp.egg.android.request.volley.JacksonRequest.java

@Override
protected Response<JsonNode> parseNetworkResponse(NetworkResponse response) {
    try {//from ww  w.j  av a 2 s.  co m
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

        ObjectMapper om = new ObjectMapper();
        JsonNode jnode = om.readTree(jsonString);

        //            String jsonString =
        //                new String(response.data, HttpHeaderParser.parseCharset(response.headers));

        return Response.success(jnode, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JsonProcessingException e) {
        return Response.error(new ParseError(e));
    } catch (IOException e) {
        return Response.error(new ParseError(e));
    }
}

From source file:org.forgerock.openig.migrate.Main.java

void execute(OutputStream stream) throws Exception {

    // Pre-parse the original files with JSON-Simple parser (which is more lenient than Jackson's one)
    File source = new File(sources.get(0));
    JSONParser parser = new JSONParser();
    JSONObject object = (JSONObject) parser.parse(new FileReader(source));

    // Then serialize again the structure (should clean up the JSON)
    StringWriter writer = new StringWriter();
    object.writeJSONString(writer);/*w w  w.j a  v  a2s .co  m*/

    // Load migration actions to apply in order
    List<Action> actions = loadActions();

    // Parse the cleaned-up content with Jackson this time
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = (ObjectNode) mapper.readTree(writer.toString());

    // Apply migration actions
    for (Action action : actions) {
        node = action.migrate(node);
    }

    // Serialize the migrated content on the given stream (with pretty printer)
    DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
    prettyPrinter.indentArraysWith(DefaultPrettyPrinter.Lf2SpacesIndenter.instance);
    mapper.writeTree(factory.createGenerator(stream).setPrettyPrinter(prettyPrinter), node);
}

From source file:com.evrythng.java.wrapper.mapping.PropertyDeserializer.java

@Override
public Property<?> deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode valueNode = node.get(Property.FIELD_VALUE);
    if (valueNode == null) {
        throw new JsonMappingException("Cannot deserialize property without value field");
    }//from   ww  w .jav  a2 s  .  c  o  m
    Object value = getFieldValue(valueNode);
    Property.Type type = Property.Type.forPropertyValue(value);
    Class<? extends Property<?>> propertyClass = propertyClassForType(type);
    return mapper.readValue(node.toString(), propertyClass);
}

From source file:com.evrythng.java.wrapper.mapping.BatchPopulatingTaskInputParametersDeserializer.java

@Override
public BatchPopulatingTask.InputParameters deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode typeNode = node.get(BatchPopulatingTask.InputParameters.FIELD_TYPE);
    if (typeNode == null) {
        throw new JsonMappingException("Cannot deserialize adi generation input parameters without type field");
    }//from w w w  .ja v a  2 s.c  o  m
    String typeRaw = getFieldValue(typeNode);
    Class<? extends BatchPopulatingTask.InputParameters> subtypeClass = classForType(
            BatchPopulatingTask.InputParameters.Type.valueOf(typeRaw.toUpperCase()));
    return mapper.readValue(node.toString(), subtypeClass);
}

From source file:net.mostlyharmless.jghservice.connector.github.ModifyComment.java

@Override
public Integer processResponse(String jsonResponse) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(jsonResponse);
    return root.get("id").asInt();
}

From source file:org.fusesource.restygwt.examples.server.GreetingServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    System.out.println("Sending Hello World");
    try {//from   w  w  w .j  a  v a  2s .c o m
        ObjectMapper mapper = new ObjectMapper();
        JsonNode helloJsonNode = mapper.readTree(helloWorldJson);
        mapper.writeValue(resp.getOutputStream(), helloJsonNode);
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        System.out.flush();
        System.err.flush();
    }
}