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

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

Introduction

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

Prototype

public void writeValue(Writer w, Object value)
        throws IOException, JsonGenerationException, JsonMappingException 

Source Link

Document

Method that can be used to serialize any Java value as JSON output, using Writer provided.

Usage

From source file:pushandroid.POST2GCM.java

public static void post(Content content) {

    try {/*from   w ww .j ava  2 s.  c o m*/

        // 1. URL
        URL url = new URL(URL);

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);

        conn.setDoOutput(true);

        // 5. Add JSON data into POST request body
        //`5.1 Use Jackson object mapper to convert Contnet object into JSON
        ObjectMapper mapper = new ObjectMapper();

        // 5.2 Get connection output stream
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

        // 5.3 Copy Content "JSON" into
        mapper.writeValue(wr, content);

        // 5.4 Send the request
        wr.flush();

        // 5.5 close
        wr.close();

        // 6. Get the response
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 7. Print result
        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.ingenieux.lambada.runtime.LambadaUtils.java

public static <I, O> void wrap(ObjectMapper mapper, InputStream inputStream, OutputStream outputStream,
        Class<I> inputClass, BodyFunction<PassthroughRequest<I>, O> func) throws Exception {
    PassthroughRequest<I> request = getRequest(mapper, inputClass, inputStream);

    O output = func.execute(request);//from   www  . ja  v  a  2s.co  m

    mapper.writeValue(outputStream, output);
}

From source file:br.com.dgimenes.jsonlibscomparison.JSONLibsTest.java

private static String encodeWithJACKSONJAXB(SalesJAXB salesAnnotatedWithJAXB)
        throws JsonGenerationException, JsonMappingException, IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("deprecation")
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // enables "JAXB annotations only" mode
    mapper.setAnnotationIntrospector(introspector);
    mapper.writeValue(outputStream, salesAnnotatedWithJAXB);
    return outputStream.toString();
}

From source file:com.aerofs.baseline.admin.Commands.java

/**
 * Prints pretty-printed or non-pretty-printed JSON to an output stream
 * based on whether a query parameter named {@code pretty} exists.
 *
 * @param mapper {@code ObjectMapper} used to generate the output JSON
 * @param writer {@code OutputStream} to which the output is written
 * @param queryParameters query parameters from the request
 * @param json Jackson-serialized JSON object
 *
 * @throws java.io.IOException if the object cannot be transformed to JSON or written to the output
 *///w  w  w.  j  a  va  2  s. co  m
public static void outputFormattedJson(ObjectMapper mapper, Writer writer,
        MultivaluedMap<String, String> queryParameters, @Nullable Object json) throws IOException {
    if (json == null) {
        return;
    }

    if (shouldPrettyPrint(queryParameters)) {
        mapper.writerWithDefaultPrettyPrinter().writeValue(writer, json);
    } else {
        mapper.writeValue(writer, json);
    }
}

From source file:org.mortbay.jetty.load.generator.starter.AbstractLoadGeneratorStarter.java

protected static String writeAsJsonTmp(Resource resource) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    Path tmpPath = Files.createTempFile("profile", ".tmp");
    objectMapper.writeValue(tmpPath.toFile(), resource);
    return tmpPath.toString();
}

From source file:java2typescript.jaxrs.model.RestService.java

/**
 * Dump a JSON representation of the REST services
 *//*w ww. j av a  2  s.  c  om*/
static public void toJSON(Collection<RestService> services, Writer writer)
        throws JsonGenerationException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(INDENT_OUTPUT, true);

    List<RestService> restServivcesWithoutParams = new ArrayList<RestService>();
    for (RestService restService : services) {
        restServivcesWithoutParams.add(copyWithoutContextParams(restService));
    }

    mapper.writeValue(writer, restServivcesWithoutParams);
}

From source file:com.msopentech.odatajclient.engine.data.Serializer.java

private static void json(final Element element, final Writer writer) {
    try {/*from w  w  w. j a v  a2 s  .  c  o m*/
        final ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
        final JSONProperty property = new JSONProperty();
        property.setContent(element);
        mapper.writeValue(writer, property);
    } catch (IOException e) {
        throw new IllegalArgumentException("While serializing JSON property", e);
    }
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * Convert the object to JSON.//from   w  w w.  j av a 2 s  .c o  m
 * 
 * @param object
 *            the object to be converted
 * @return a string with the encoded json.
 * @throws IOException
 *             throws an IOException if the object could not be converted.
 */
public static String objectToJSON(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mapper.writeValue(baos, object);
    return new String(baos.toString("UTF-8"));
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * This will clone the given object and return a complete copy. This is
 * especially useful to eagerly load all the elements in a collection when
 * the object is fetched from hibernate. The transaction that was used to
 * fetch the original object will need to be open to fetch any additional
 * fields./*from w w w . j  a  v  a  2  s .  c o m*/
 * 
 * @param object
 *            the object that needs to be cloned
 * @return the cloned object with all fields filled in
 * @throws IOException
 *             throws an IOException if the object could not be cloned.
 */
@SuppressWarnings("unchecked")
public static <T> T cloneObject(T object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mapper.writeValue(baos, object);

    return removeDuplicate((T) mapper.readValue(baos.toByteArray(), object.getClass()));
}

From source file:de.javagl.jgltf.model.io.GltfUtils.java

/**
 * Creates a deep copy of the given {@link GlTF}.<br>
 * <br>//from   w w  w .j  a v a 2s  .c  o m
 * Note: Some details about the copy are not specified. E.g. whether
 * values that are mapped to <code>null</code> are still contained
 * in the copy. The goal of this method is to create a copy that is,
 * as far as reasonably possible, "structurally equivalent" to the
 * given input.
 * 
 * @param gltf The input 
 * @return The copy
 * @throws GltfException If the copy can not be created
 */
static GlTF copy(GlTF gltf) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        objectMapper.writeValue(baos, gltf);
        return objectMapper.readValue(baos.toByteArray(), GlTF.class);
    } catch (IOException e) {
        throw new GltfException("Could not copy glTF", e);
    }
}