List of usage examples for com.fasterxml.jackson.databind ObjectMapper createObjectNode
@Override
public ObjectNode createObjectNode()
Note: return type is co-variant, as basic ObjectCodec abstraction can not refer to concrete node types (as it's part of core package, whereas impls are part of mapper package)
From source file:com.infinities.skyport.util.JsonUtil.java
public static String toJson(boolean insertResponseCode, String msg, Object object, Class<? extends Views.Short> view) { ObjectMapper mapper = getObjectMapper(); ObjectWriter writer = mapper.writerWithView(view).withDefaultPrettyPrinter(); JsonNode rootNode = mapper.createObjectNode(); try {//from ww w . j av a 2 s . co m if (object == null || "".equals(object)) { object = mapper.createObjectNode(); } String temp = writer.writeValueAsString(object); rootNode = mapper.readTree(temp); } catch (Exception e) { logger.error("json parsing failed", e); } ObjectNode root = getObjectMapper().createObjectNode(); root.put(JsonConstants.STATUS, insertResponseCode ? 1 : 0).put(JsonConstants.MSG, msg) .put(JsonConstants._DATA, rootNode); try { return getObjectMapper().configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false) .writeValueAsString(root); } catch (Exception e) { logger.error("json parsing failed", e); throw new RuntimeException(e); } }
From source file:com.infinities.skyport.util.JsonUtil.java
public static String toJson(Object object, Class<? extends Views.Short> view) { ObjectMapper mapper = getObjectMapper(); ObjectWriter writer = mapper.writerWithView(view).withDefaultPrettyPrinter(); try {// www . j a v a2 s . c o m if (object == null || "".equals(object)) { object = mapper.createObjectNode(); } return writer.writeValueAsString(object); } catch (Exception e) { logger.error("json parsing failed", e); throw new RuntimeException(e); } }
From source file:parser.JsonWriter.java
/** * Creates json file for the cloudDSFPlus with all new attributes. * /*from w w w. j a v a 2 s . c om*/ * @param workbook * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ private static void writeCloudDSFPlusJson(XSSFWorkbook workbook) throws JsonGenerationException, JsonMappingException, IOException { // instantiate parser for CloudDSFPlus and read excel CloudDSFPlusParser cloudDSFPlusParser = new CloudDSFPlusParser(workbook); CloudDSF cdsf = cloudDSFPlusParser.readExcel(); // check the internal consistency and if successfull serialize data if (cdsf.checkSanity()) { // Helper Method // cdsf.printCloudDSF(); // Jackson objectmapper and settings ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); // Ignore missing getters to serialize all values mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE)); mapper.setSerializationInclusion(Include.NON_NULL); // create json structure JsonNode rootNode = mapper.createObjectNode(); ((ObjectNode) rootNode).putPOJO("cdsfPlus", cdsf); ((ObjectNode) rootNode).putPOJO("links", cdsf.getInfluencingDecisions()); ((ObjectNode) rootNode).putPOJO("outcomeLinks", cdsf.getInfluencingOutcomes()); // Serialize CloudDSFPlus into json file File file = new File("cloudDSFPlus.json"); mapper.writeValue(file, rootNode); System.out.println("Knowledge Base has been successfully verified and exported"); } else { // knowledge base is not valid abort serialization System.out.println("The knowledge base is not valid"); } }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
public static String getMessageBody(Message message) { try {/* www. j a va2 s. co m*/ if (message instanceof MapMessage) { MapMessage mm = (MapMessage) message; ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); @SuppressWarnings("unchecked") Enumeration<String> e = mm.getMapNames(); while (e.hasMoreElements()) { String field = e.nextElement(); root.set(field, mapper.convertValue(mm.getObject(field), JsonNode.class)); } return mapper.writer().writeValueAsString(root); } else if (message instanceof TextMessage) { TextMessage tm = (TextMessage) message; return tm.getText(); } else if (message instanceof BytesMessage) { BytesMessage bm = (BytesMessage) message; byte[] bytes = new byte[(int) bm.getBodyLength()]; if (bm.readBytes(bytes) == bm.getBodyLength()) { return new String(bytes); } } else { log.log(Level.SEVERE, "Unsupported message type:\n" + formatMessage(message)); } } catch (Exception e) { log.log(Level.SEVERE, "Unhandled exception retrieving message body:\n" + formatMessage(message), e); } return ""; }
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
public static String formatMessage(Message message) { StringBuilder sb = new StringBuilder(); try {//from w ww.j av a 2s.c om String headers = formatHeaders(message); if (headers.length() > 0) { sb.append("Message Headers:\n"); sb.append(headers); } sb.append("Message Properties:\n"); @SuppressWarnings("unchecked") Enumeration<String> propNames = message.getPropertyNames(); while (propNames.hasMoreElements()) { String propertyName = propNames.nextElement(); sb.append(" "); sb.append(propertyName); sb.append(": "); if (message.getObjectProperty(propertyName) != null) { sb.append(message.getObjectProperty(propertyName).toString()); } sb.append("\n"); } sb.append("Message Content:\n"); if (message instanceof TextMessage) { sb.append(((TextMessage) message).getText()); } else if (message instanceof MapMessage) { MapMessage mm = (MapMessage) message; ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); @SuppressWarnings("unchecked") Enumeration<String> e = mm.getMapNames(); while (e.hasMoreElements()) { String field = e.nextElement(); root.put(field, mapper.convertValue(mm.getObject(field), JsonNode.class)); } sb.append(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)); } else if (message instanceof BytesMessage) { BytesMessage bm = (BytesMessage) message; bm.reset(); byte[] bytes = new byte[(int) bm.getBodyLength()]; if (bm.readBytes(bytes) == bm.getBodyLength()) { sb.append(new String(bytes)); } } else { sb.append(" Unhandled message type: " + message.getJMSType()); } } catch (Exception e) { log.log(Level.SEVERE, "Unable to format message:", e); } return sb.toString(); }
From source file:parser.JsonWriter.java
/** * Generates json file for the CloudDSF avoiding any unnecessary attribute serialization. * /* www.ja v a 2 s .c o m*/ * @param workbook * @throws JsonGenerationException * @throws JsonMappingException * @throws IOException */ private static void writeCloudDSFJson(XSSFWorkbook workbook) throws JsonGenerationException, JsonMappingException, IOException { // Instantiate parser to parse file for CloudDSF CloudDSFParser parser = new CloudDSFParser(workbook); // CloudDSF object representing all necessary information CloudDSF cdsf = parser.readExcel(); // Helper Method to check content // cdsf.printCloudDSF(); // Create task tree for legacy visualizations TaskTree taskTree = new TaskTree(); taskTree.setTasks(cdsf.getTasks()); // Jackson objectmapper and settings ObjectMapper mapper = new ObjectMapper(); // Pretty Print mapper.enable(SerializationFeature.INDENT_OUTPUT); // If getter is found values will be serialized avoiding unnecessary attributes mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.DEFAULT) .withGetterVisibility(JsonAutoDetect.Visibility.DEFAULT)); // Ignore fields with null values to avoid serialization of empty lists mapper.setSerializationInclusion(Include.NON_NULL); // Write all relations into one list to conform to legacy implementation cdsf.setInfluencingRelations(); // create json root node and add json objects JsonNode rootNode = mapper.createObjectNode(); ((ObjectNode) rootNode).putPOJO("decisionTree", cdsf); ((ObjectNode) rootNode).putPOJO("taskTree", taskTree); ((ObjectNode) rootNode).putPOJO("linksArray", cdsf.getInfluencingRelations()); // serialize CloudDSF into file File file = new File("cloudDSF.json"); mapper.writeValue(file, rootNode); }
From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java
public static ObjectNode buildSchemaNode(final ObjectMapper objectMapper, final URI schemaUri, final SchemaLoader schemaLoader, final Set<URI> addedBaseSchemaUris) { final Prototype prototype = schemaLoader.getPrototype(schemaUri); if (prototype == null) { return null; }/* w w w . j a v a2 s.c o m*/ final ObjectNode schemaNode = objectMapper.createObjectNode(); schemaNode.put(PropertyName.localName.name(), prototype.getUniqueName().getLocalName()); schemaNode.put(PropertyName.title.name(), prototype.getTitle()); schemaNode.put(PropertyName.uri.name(), schemaUri.toString()); schemaNode.put(PropertyName.version.name(), prototype.getVersion()); String titleSlotName = prototype.getTitleSlotName(); if (StringUtils.isNotBlank(titleSlotName)) { schemaNode.put(PropertyName.titleSlotName.name(), titleSlotName); } else { titleSlotName = getTitleSlotName(schemaUri, schemaLoader); if (StringUtils.isNotBlank(titleSlotName)) { schemaNode.put(PropertyName.titleSlotName.name(), titleSlotName); } } final Set<String> allSlotNames = prototype.getAllSlotNames(); if (allSlotNames != null && !allSlotNames.isEmpty()) { final ArrayNode propertyNamesNode = objectMapper.createArrayNode(); for (final String slotName : allSlotNames) { final ProtoSlot protoSlot = prototype.getProtoSlot(slotName); if (protoSlot instanceof LinkProtoSlot) { continue; } if (protoSlot.getDeclaringSchemaUri().equals(schemaUri)) { propertyNamesNode.add(slotName); } } if (propertyNamesNode.size() > 0) { schemaNode.put(PropertyName.propertyNames.name(), propertyNamesNode); } } final Set<String> keySlotNames = prototype.getDeclaredKeySlotNames(); if (keySlotNames != null && !keySlotNames.isEmpty()) { final ArrayNode keyPropertyNamesNode = objectMapper.createArrayNode(); for (final String keySlotName : keySlotNames) { keyPropertyNamesNode.add(keySlotName); } if (keyPropertyNamesNode.size() > 0) { schemaNode.put(PropertyName.keyPropertyNames.name(), keyPropertyNamesNode); } } final Set<String> allKeySlotNames = prototype.getAllKeySlotNames(); final ArrayNode allKeySlotNamesNode = objectMapper.createArrayNode(); schemaNode.put(PropertyName.allKeySlotNames.name(), allKeySlotNamesNode); for (final String keySlotName : allKeySlotNames) { allKeySlotNamesNode.add(keySlotName); } final Set<String> comparablePropertyNames = prototype.getComparableSlotNames(); if (comparablePropertyNames != null && !comparablePropertyNames.isEmpty()) { final ArrayNode comparablePropertyNamesNode = objectMapper.createArrayNode(); for (final String comparablePropertyName : comparablePropertyNames) { comparablePropertyNamesNode.add(comparablePropertyName); } if (comparablePropertyNamesNode.size() > 0) { schemaNode.put(PropertyName.comparablePropertyNames.name(), comparablePropertyNamesNode); } } final Map<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots(); if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) { final ArrayNode linkNamesNode = objectMapper.createArrayNode(); for (final LinkProtoSlot linkProtoSlot : linkProtoSlots.values()) { if (linkProtoSlot.getDeclaringSchemaUri().equals(schemaUri)) { linkNamesNode.add(linkProtoSlot.getName()); } } if (linkNamesNode.size() > 0) { schemaNode.put(PropertyName.linkNames.name(), linkNamesNode); } } final Set<URI> declaredBaseSchemaUris = prototype.getDeclaredBaseSchemaUris(); if (declaredBaseSchemaUris != null && !declaredBaseSchemaUris.isEmpty() && addedBaseSchemaUris != null) { final ArrayNode baseSchemasNode = objectMapper.createArrayNode(); for (final URI baseSchemaUri : declaredBaseSchemaUris) { if (!addedBaseSchemaUris.contains(baseSchemaUri)) { final ObjectNode baseSchemaNode = buildSchemaNode(objectMapper, baseSchemaUri, schemaLoader, addedBaseSchemaUris); baseSchemasNode.add(baseSchemaNode); addedBaseSchemaUris.add(baseSchemaUri); } } if (baseSchemasNode.size() > 0) { schemaNode.put(PropertyName.baseSchemas.name(), baseSchemasNode); } } return schemaNode; }
From source file:org.isaacphysics.labs.chemistry.checker.RunParser.java
public String toJSON(String input, String result) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode node1 = mapper.createObjectNode(); node1.put("result", result); node1.put("input", input); return mapper.writeValueAsString(node1); }
From source file:org.activiti.engine.dynamic.BasePropertiesParser.java
@Override public ObjectNode parseElement(FlowElement flowElement, ObjectNode flowElementNode, ObjectMapper mapper) { ObjectNode resultNode = mapper.createObjectNode(); resultNode.put(ELEMENT_ID, flowElement.getId()); resultNode.put(ELEMENT_TYPE, flowElement.getClass().getSimpleName()); if (supports(flowElement)) { resultNode.set(ELEMENT_PROPERTIES, createPropertiesNode(flowElement, flowElementNode, mapper)); }//from w w w. j a va2s .co m return resultNode; }
From source file:com.collective.celos.servlet.JSONWorkflowServletTest.java
@Test public void jsonCorrectlyProduced() throws Exception { ScheduledTime t1 = new ScheduledTime("2013-12-20T20:00:00.000Z"); ScheduledTime t2 = new ScheduledTime("2013-12-20T21:00:00.000Z"); WorkflowID wfID = new WorkflowID("foobar"); SlotState s1 = new SlotState(new SlotID(wfID, t1), SlotState.Status.READY); SlotState s2 = new SlotState(new SlotID(wfID, t2), SlotState.Status.RUNNING, "external-ID", 4); List<SlotState> states = new LinkedList<SlotState>(); states.add(s1);/*from w w w. ja v a 2 s .c om*/ states.add(s2); ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put(t1.toString(), s1.toJSONNode()); node.put(t2.toString(), s2.toJSONNode()); Assert.assertEquals(node, new JSONWorkflowServlet().createJSONObject(states)); }