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

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

Introduction

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

Prototype

public ObjectMapper() 

Source Link

Document

Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider , and BeanSerializerFactory as its SerializerFactory .

Usage

From source file:json_csv.JSON2CSV.java

public static void main(String myHelpers[]) {

    // These code snippets use an open-source library. http://unirest.io/java
    ObjectMapper mapper = new ObjectMapper();
    JSON2CSV run = new JSON2CSV();

    try {//  w w w. j  av a  2  s  . c  o m

        run.ibw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ingredient.csv"), "UTF-8"));
        run.rbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("recipe.csv"), "UTF-8"));
        run.cbw = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream("cuisineRecipe.csv"), "UTF-8"));

        for (int i = 0; i < 100; i++) {

            // These code snippets use an open-source library. http://unirest.io/java
            HttpResponse<JsonNode> response = Unirest.get(
                    "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/random?limitLicense=false&number=100")
                    .header("X-Mashape-Key", "dkK9bOKEkNmshOLDuw9rHq59F0Twp1fvyxcjsn99AoUm6XvMfC")
                    .header("Accept", "application/json").asJson();

            // retrieve the parsed JSONObject from the response
            JSONObject myObj = response.getBody().getObject();

            JSONArray results = myObj.getJSONArray("recipes");

            run.parseRecipe(results);

            run.printRecipeToCSV();

            run.printCuisineLookupTable(run.recipes);
        }

        run.rbw.flush();
        run.rbw.close();

        run.ibw.flush();
        run.ibw.close();

        run.cbw.flush();
        run.cbw.close();

    } catch (UnirestException ue) {

        ue.printStackTrace();

    } catch (JSONException e) {

        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.bimserver.javamodelchecker.WriteToJson.java

public static void main(String[] args) {
    try {/*w  ww.j av  a 2 s .  com*/
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode rootNode = objectMapper.createObjectNode();
        ArrayNode array = objectMapper.createArrayNode();
        rootNode.set("modelcheckers", array);

        ObjectNode objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Check window widths");
        objectNode.put("description", "Check window widths");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code",
                changeClassName(
                        FileUtils.readFileToString(
                                new File("src/org/bimserver/javamodelchecker/WindowWidthChecker.java")),
                        "WindowWidthChecker"));

        objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Pass always");
        objectNode.put("description", "Pass always");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code", changeClassName(
                FileUtils.readFileToString(new File("src/org/bimserver/javamodelchecker/PassAlways.java")),
                "PassAlways"));

        objectNode = objectMapper.createObjectNode();
        array.add(objectNode);
        objectNode.put("name", "Fail always");
        objectNode.put("description", "Fail always");
        objectNode.put("modelCheckerPluginClassName", "org.bimserver.javamodelchecker.JavaModelCheckerPlugin");
        objectNode.put("code", changeClassName(
                FileUtils.readFileToString(new File("src/org/bimserver/javamodelchecker/FailAlways.java")),
                "FailAlways"));

        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File("modelcheckers.json"), rootNode);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.force66.json.tools.JSonSchemaGenerator.java

public static void main(String[] args) throws Exception {
    Validate.isTrue(args != null && args.length >= 2, "Usage arguments: className fileTarget");

    String className = args[0];/*  w  w  w.j a va  2s . c o  m*/
    String outputFileName = args[1];

    HyperSchemaFactoryWrapper schemaVisitor = new HyperSchemaFactoryWrapper();
    ObjectMapper mapper = new ObjectMapper();
    mapper.acceptJsonFormatVisitor(ClassUtils.getClass(className), schemaVisitor);
    JsonSchema jsonSchema = schemaVisitor.finalSchema();

    File outputFile = new File(outputFileName);
    FileUtils.write(outputFile, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema));
}

From source file:net.javacrumbs.jsonliteral.jackson2.Example.java

public static void main(String[] args) throws JsonProcessingException {
    JsonNode node = obj(one -> true, two -> obj(three -> false), string -> "value", integer -> 1, $null -> null,
            $double -> 1.1, $float -> 1.0f, array -> asList(1, "a", 3), array2 -> array("a", "b", "c") // you can use array method
    );/*  w  ww  .j a  v a  2 s  .  c  om*/

    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(node));

    System.out.println("------");

    String value = "valueFromVariable";

    JsonNode node2 = obj(
            root -> obj(value1 -> "value", value2 -> obj(value3 -> 1, value4 -> obj(test -> value))));

    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(node2));
}

From source file:org.glowroot.benchmark.ResultFormatter.java

public static void main(String[] args) throws IOException {
    File resultFile = new File(args[0]);

    Scores scores = new Scores();
    double baselineStartupTime = -1;
    double glowrootStartupTime = -1;

    ObjectMapper mapper = new ObjectMapper();
    String content = Files.toString(resultFile, Charsets.UTF_8);
    content = content.replaceAll("\n", " ");
    ArrayNode results = (ArrayNode) mapper.readTree(content);
    for (JsonNode result : results) {
        String benchmark = result.get("benchmark").asText();
        benchmark = benchmark.substring(0, benchmark.lastIndexOf('.'));
        ObjectNode primaryMetric = (ObjectNode) result.get("primaryMetric");
        double score = primaryMetric.get("score").asDouble();
        if (benchmark.equals(StartupBenchmark.class.getName())) {
            baselineStartupTime = score;
            continue;
        } else if (benchmark.equals(StartupWithGlowrootBenchmark.class.getName())) {
            glowrootStartupTime = score;
            continue;
        }//from w  ww  . j a va  2 s. c  o m
        ObjectNode scorePercentiles = (ObjectNode) primaryMetric.get("scorePercentiles");
        double score50 = scorePercentiles.get("50.0").asDouble();
        double score95 = scorePercentiles.get("95.0").asDouble();
        double score99 = scorePercentiles.get("99.0").asDouble();
        double score999 = scorePercentiles.get("99.9").asDouble();
        double score9999 = scorePercentiles.get("99.99").asDouble();
        double allocatedBytes = getAllocatedBytes(result);
        if (benchmark.equals(ServletBenchmark.class.getName())) {
            scores.baselineResponseTimeAvg = score;
            scores.baselineResponseTime50 = score50;
            scores.baselineResponseTime95 = score95;
            scores.baselineResponseTime99 = score99;
            scores.baselineResponseTime999 = score999;
            scores.baselineResponseTime9999 = score9999;
            scores.baselineAllocatedBytes = allocatedBytes;
        } else if (benchmark.equals(ServletWithGlowrootBenchmark.class.getName())) {
            scores.glowrootResponseTimeAvg = score;
            scores.glowrootResponseTime50 = score50;
            scores.glowrootResponseTime95 = score95;
            scores.glowrootResponseTime99 = score99;
            scores.glowrootResponseTime999 = score999;
            scores.glowrootResponseTime9999 = score9999;
            scores.glowrootAllocatedBytes = allocatedBytes;
        } else {
            throw new AssertionError(benchmark);
        }
    }
    System.out.println();
    printScores(scores);
    if (baselineStartupTime != -1) {
        System.out.println("STARTUP");
        System.out.format("%25s%14s%14s%n", "", "baseline", "glowroot");
        printLine("Startup time (avg)", "ms", baselineStartupTime, glowrootStartupTime);
    }
    System.out.println();
}

From source file:com.codekul.simpleboot.Main.java

public static void main(String[] args) throws Exception {

    ApplicationContext context = SpringApplication.run(Main.class, args);

    for (String bean : context.getBeanDefinitionNames()) {

        System.out.println("com.codekul.simpleboot.Main.main() Beans -> " + bean);
    }//w ww  .j  a v a  2s  . co m

    Car car = (Car) context.getBean("carMy");
    car.setCarCity("Pune");
    car.setCarName("AUdi");

    System.out.println("Car is -> " + car.toString());

    Animal animal = (Animal) context.getBean("animal");
    animal.setCarMy(car);

    animal.setCountry("india");
    System.out.println("Animal Country - " + animal.getCountry());

    Car myCar = new Car(car);

    ObjectMapper objectMapper = new ObjectMapper();
    String carJson = objectMapper.writeValueAsString(myCar);

    System.out.println("Car JSON - " + carJson);
}

From source file:cz.hobrasoft.pdfmu.jackson.SchemaGenerator.java

public static void main(String[] args) throws JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT); // nice formatting

    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

    Map<String, Type> types = new HashMap<>();
    types.put("RpcResponse", RpcResponse.class);
    types.put("result/inspect", Inspect.class);
    types.put("result/version set", VersionSet.class);
    types.put("result/signature add", SignatureAdd.class);
    types.put("result/empty", EmptyResult.class);

    for (Map.Entry<String, Type> e : types.entrySet()) {
        String name = e.getKey();
        String filename = String.format("schema/%s.json", name);
        Type type = e.getValue();
        mapper.acceptJsonFormatVisitor(mapper.constructType(type), visitor);
        JsonSchema jsonSchema = visitor.finalSchema();
        mapper.writeValue(new File(filename), jsonSchema);
    }//from www . j av a2 s  . c o  m
}

From source file:com.iflytek.edu.cloud.frame.doc.BuildDocMain.java

public static void main(String[] args) throws Exception {
    ServiceDocBuilder docBuilder = new ServiceDocBuilder();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    File jsonFile = getJsonFile();
    JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonFile, JsonEncoding.UTF8);
    jsonGenerator.writeObject(docBuilder.buildDoc());

    LOGGER.info("?API?" + jsonFile.getPath());
}

From source file:test.jackson.JacksonNsgiRegister.java

public static void main(String[] args) throws IOException {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    String ngsiRcr = new String(Files.readAllBytes(Paths.get(NGSI_FILE)));

    RegisterContextRequest rcr = objectMapper.readValue(ngsiRcr, RegisterContextRequest.class);

    System.out.println(objectMapper.writeValueAsString(rcr));

    LinkedHashMap association = (LinkedHashMap) rcr.getContextRegistration().get(0).getContextMetadata().get(0)
            .getValue();/*from   w  ww .  j  ava 2s  .  co  m*/
    Association assocObject = objectMapper.convertValue(association, Association.class);
    System.out.println(assocObject.getAttributeAssociation().get(0).getSourceAttribute());

    rcr.getContextRegistration().get(0).getContextRegistrationAttribute().get(1).getContextMetadata().get(0);

    //        System.out.println(rcr.getContextRegistration().get(0).getContextMetadata().get(0).getValue().getClass().getCanonicalName());

    //        String assocJson = objectMapper.writeValueAsString(association);
    //        Value assocObject =  objectMapper.readValue(objectMapper.writeValueAsString(association), Value.class);
    //        System.out.println(association.values().toString());
    //        System.out.println(assocJson);

}

From source file:ch.rasc.wampspring.demo.client.CallClient.java

public static void main(String[] args) throws InterruptedException {
    WebSocketClient webSocketClient = new StandardWebSocketClient();
    JsonFactory jsonFactory = new MappingJsonFactory(new ObjectMapper());

    CountDownLatch latch = new CountDownLatch(1_000_000);
    TestTextWebSocketHandler handler = new TestTextWebSocketHandler(jsonFactory, latch);

    Long[] start = new Long[1];
    ListenableFuture<WebSocketSession> future = webSocketClient.doHandshake(handler,
            "ws://localhost:8080/wamp");
    future.addCallback(wss -> {/*w  w w  .j ava 2s.  co m*/
        start[0] = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000; i++) {

            CallMessage callMessage = new CallMessage(UUID.randomUUID().toString(), "testService.sum", i,
                    i + 1);
            try {
                wss.sendMessage(new TextMessage(callMessage.toJson(jsonFactory)));
            } catch (Exception e) {
                System.out.println("ERROR SENDING CALLMESSAGE" + e);
                latch.countDown();
            }
        }

    }, t -> {
        System.out.println("DO HANDSHAKE ERROR: " + t);
        System.exit(1);
    });

    if (!latch.await(3, TimeUnit.MINUTES)) {
        System.out.println("SOMETHING WENT WRONG");
    }

    System.out.println((System.currentTimeMillis() - start[0]) / 1000 + " seconds");
    System.out.println("SUCCESS: " + handler.getSuccess());
    System.out.println("ERROR  : " + handler.getError());
}