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:ai.general.interbot.ConfigFiles.java

/**
 * Saves a configuration file. The filename should specify only the configuration filename.
 * The file will be saved to the configuration file directory that is appropriate for the
 * current context./* w ww .j a  v  a 2s . c om*/
 *
 * The configuration object will be saved in JSON format. The configuration object must be a
 * POJO class that is serializable into JSON.
 *
 * If the .json extension is not specified in the filename, it will be appended to the filename.
 *
 * @param filename The name of the configuration file, excluding extension and directory.
 * @param configuration The object representing the configuration to be saved.
 * @return True if the file was successfully saved.
 */
public boolean save(String filename, Object configuration) {
    if (!filename.endsWith(".json")) {
        filename = filename + ".json";
    }
    ObjectMapper json_generator = new ObjectMapper();
    try {
        json_generator.writeValue(new File(InterbotPaths.getConfigDirectory() + filename), configuration);
        return true;
    } catch (IOException e) {
        log.catching(Level.DEBUG, e);
        return false;
    }
}

From source file:com.boundary.plugin.sdk.jmx.MBeansTransformerTest.java

@Test
public void testMBeansTransformer() {
    MBeanTransform<MBeanMap> transform = new MBeanMapTransform();
    JMXClient client = new JMXClient();
    try {/*from   w  ww  .ja va 2  s .  c  om*/
        client.connect("localhost", 9991);
        MBeansTransformer<MBeanMap> transformer = new MBeansTransformer<MBeanMap>(client, transform, "FOO");
        transformer.transform();

        MBeanMap map = transformer.export();

        for (MBeanEntry entry : map.getMap()) {
            System.out.println(entry);
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(System.out, map);

    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.github.retz.cli.CommandGetApp.java

@Override
public int handle(ClientCLIConfig fileConfig, boolean verbose) throws Throwable {
    LOG.debug("Configuration: {}", fileConfig.toString());

    try (Client webClient = Client.newBuilder(fileConfig.getUri())
            .setAuthenticator(fileConfig.getAuthenticator()).checkCert(!fileConfig.insecure())
            .setVerboseLog(verbose).build()) {

        Response res = webClient.getApp(appName);
        if (res instanceof ErrorResponse) {
            LOG.error(res.status());//from  w w  w  .j  a  v a  2  s  . c  om
        } else if (res instanceof GetAppResponse) {
            GetAppResponse getAppResponse = (GetAppResponse) res;
            Application app = getAppResponse.application();

            ObjectMapper mapper = new ObjectMapper();
            mapper.registerModule(new Jdk8Module());
            mapper.writeValue(System.out, app);
            System.out.println();
            return 0;
        }
    }
    return -1;
}

From source file:com.boundary.plugin.sdk.jmx.MBeansTransformerTest.java

@Test
public void testMetricDefinitionTransform() {
    transformer.transform();//from w ww.j av  a2 s .com
    MetricDefinitionList list = transform.getExport();

    ObjectMapper mapper = new ObjectMapper();
    try {
        mapper.writeValue(System.out, list);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.jaspersoft.jasperserver.war.webflow.JsonModelView.java

public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("rendering json model view");
    }//from   ww  w.  j a  v  a2s. c o m

    LinkedHashMap<String, Object> responseMap = new LinkedHashMap<String, Object>();
    for (String modelName : modelNames) {
        Object modelObject = model.get(modelName);
        if (modelObject != null) {
            responseMap.put(modelName, modelObject);
        }
    }

    response.setContentType("application/json; charset=UTF-8");

    ObjectMapper jsonMapper = new ObjectMapper();
    ServletOutputStream out = response.getOutputStream();
    jsonMapper.writeValue(out, responseMap);
}

From source file:org.soulwing.prospecto.jackson.ViewDeserializer.java

@Override
public View deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException, JsonProcessingException {

    final JsonNode tree = jsonParser.readValueAsTree();
    final ObjectMapper mapper = new ObjectMapper();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    mapper.writeValue(outputStream, tree);

    final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    return readerFactory.newReader(inputStream).readView();
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCRegistrar.java

private void writeToFile(AuthClientHandler.ImplicitClient client, String path) throws IOException {
    Map<String, Object> clientJson = new HashMap<String, Object>();

    clientJson.put("ClientID", client.clientID);
    clientJson.put("LoginURI", client.loginURI);
    clientJson.put("LogoutURI", client.logoutURI);

    ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(new File(path), clientJson);
}

From source file:com.basistech.rosette.dm.json.plain.DefaultValuesVisibleTest.java

@Test
public void checkVisible() throws Exception {
    AnnotatedText.Builder builder = new AnnotatedText.Builder();
    builder.data("George Washington slept here.");
    ListAttribute.Builder<Entity> entityListBuilder = new ListAttribute.Builder<>(Entity.class);
    //int startOffset, int endOffset, String entityType)
    Mention.Builder mentionBuilder = new Mention.Builder(0, 17);
    mentionBuilder.confidence(null); // null is the official default, but null is never rendered, default or not.
    Entity.Builder entityBuilder = new Entity.Builder();
    entityBuilder.mention(mentionBuilder.build());
    entityListBuilder.add(entityBuilder.build());
    builder.entities(entityListBuilder.build());

    AnnotatedText text = builder.build();

    ObjectMapper mapper = objectMapper();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    mapper.writeValue(byteArrayOutputStream, text); // serialize

    // now bring it back
    JsonNode tree = mapper.readTree(byteArrayOutputStream.toByteArray());
    // and navigate to the problem at hand.
    ObjectNode attrsNode = (ObjectNode) tree.get("attributes");
    ObjectNode mentionsNode = (ObjectNode) attrsNode.get(KnownAttribute.ENTITY.key());
    ObjectNode mentionNode = (ObjectNode) mentionsNode.get("items").get(0);
    assertFalse(mentionNode.has("confidence"));
}

From source file:com.boundary.sdk.snmp.metric.MibTransformBase.java

public void convertToJson(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    try {//w  ww . j a v  a2s  .  c  o  m
        mapper.writeValue(System.out, obj);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.hp.autonomy.iod.client.api.search.FieldNamesTest.java

@Test
public void testGetJson() throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final Writer output = new StringWriter();
    mapper.writeValue(output, fieldNames);
    final String json = output.toString();

    assertThat(json, is(//from   w w  w  . j a va 2s  . co  m
            "{\"zero\":[{\"value\":\"1\",\"count\":1},{\"value\":\"2\",\"count\":2}],\"one\":[{\"value\":\"3\",\"count\":3},{\"value\":\"4\",\"count\":4},{\"value\":\"5\",\"count\":5}]}"));
}