Java Code Examples for org.codehaus.jackson.map.ObjectMapper#writeValueAsString()

The following examples show how to use org.codehaus.jackson.map.ObjectMapper#writeValueAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestHttpExceptionUtils.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateResponseJsonErrorUnknownException()
    throws IOException {
  Map<String, Object> json = new HashMap<String, Object>();
  json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, "FooException");
  json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, "foo.FooException");
  json.put(HttpExceptionUtils.ERROR_MESSAGE_JSON, "EX");
  Map<String, Object> response = new HashMap<String, Object>();
  response.put(HttpExceptionUtils.ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  String msg = jsonMapper.writeValueAsString(response);
  InputStream is = new ByteArrayInputStream(msg.getBytes());
  HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
  Mockito.when(conn.getErrorStream()).thenReturn(is);
  Mockito.when(conn.getResponseMessage()).thenReturn("msg");
  Mockito.when(conn.getResponseCode()).thenReturn(
      HttpURLConnection.HTTP_BAD_REQUEST);
  try {
    HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED);
    Assert.fail();
  } catch (IOException ex) {
    Assert.assertTrue(ex.getMessage().contains("EX"));
    Assert.assertTrue(ex.getMessage().contains("foo.FooException"));
  }
}
 
Example 2
Source File: Json.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public static String toJson(Object object) {
	ObjectMapper mapper = new ObjectMapper(new MyJsonFactory());
	SimpleModule module = new SimpleModule("fullcalendar", new Version(1, 0, 0, null));
	module.addSerializer(new DateTimeSerializer());
	module.addSerializer(new LocalTimeSerializer());
	mapper.registerModule(module);
	mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

	String json = null;
	try {
		json = mapper.writeValueAsString(object);
	} catch (Exception e) {
		throw new RuntimeException("Error encoding object: " + object + " into JSON string", e);
	}
	return json;
}
 
Example 3
Source File: NetworkStateSerializer.java    From zigbee4java with Apache License 2.0 6 votes vote down vote up
/**
 * Serializes the network state.
 * <p>
 * Produces a json {@link String} containing the current state of the network.
 * 
 * @param zigBeeNetwork the {@link ZigBeeNetwork}
 * @return the serialized network state as json {@link String}.
 */
public String serialize(final ZigBeeNetwork zigBeeNetwork) {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enableDefaultTyping();
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    try {
        final HashMap<ZigBeeNode, HashMap<Integer, ZigBeeEndpoint>> devices = new HashMap<ZigBeeNode, HashMap<Integer, ZigBeeEndpoint>>(zigBeeNetwork.getDevices());

        final List<ZigBeeEndpoint> endpoints = new ArrayList<ZigBeeEndpoint>();
        for (final ZigBeeNode node : devices.keySet()) {
            for (final ZigBeeEndpoint endpoint : devices.get(node).values()) {
                endpoints.add(endpoint);
            }
        }

        return objectMapper.writeValueAsString(endpoints);
    } catch (final IOException e) {
        throw new RuntimeException("Error serializing network state.", e);
    }
}
 
Example 4
Source File: ChatterCommands.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>Creates a JSON String from the message segments, ready to be consumed by the Salesforce.com API.</p>
 *
 * <p>The result is ready to be consumed by {@link #getJsonPost(String, String)}.</p>
 *
 * @param message The message which should be send to the Salesforce.com API
 * @return A (JSON) String with all the segments embedded
 * @throws JsonGenerationException
 * @throws JsonMappingException
 * @throws IOException
 */
public String getJsonPayload(Message message) throws JsonGenerationException, JsonMappingException, IOException {
    List<Map<String, String>> segments = new LinkedList<Map<String, String>>();
    for (MessageSegment segment : message.getSegments()) {
        Map<String, String> s = new HashMap<String, String>();
        s.put(MessageSegment.TYPE_KEY, segment.getTypeValue());
        s.put(segment.getSegmentKey(), segment.getSegmentValue());
        segments.add(s);
    }

    Map<String, List<Map<String, String>>> messageSegments = new HashMap<String, List<Map<String, String>>>();
    Map<String, Object> json = new LinkedHashMap<String, Object>();

    messageSegments.put("messageSegments", segments);
    json.put("body", messageSegments);
    if (message.hasAttachment()) {
    	json.put("attachment", message.getAttachment());
    }

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(json);

}
 
Example 5
Source File: DashboardInfo.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
       try {
		int mailingId = 0;
		if (req.getParameter("mailingId") != null) {
		    mailingId = Integer.parseInt(req.getParameter("mailingId"));
		}

		int companyId = 0;
		if (req.getParameter("companyId") != null) {
		    companyId = Integer.parseInt(req.getParameter("companyId"));
		}

		Map<Integer, Integer> statValues = new HashMap<>();
		if (mailingId != 0 && companyId != 0) {
		    MailingSummaryDataSet mailingSummaryDataSet = new MailingSummaryDataSet();
		    int tempTableID = mailingSummaryDataSet.prepareDashboardForCharts(mailingId, companyId);
		    List<MailingSummaryDataSet.MailingSummaryRow> mailingSummaryData = mailingSummaryDataSet.getSummaryData(tempTableID);

		    for (SendStatRow aMailingSummaryData : mailingSummaryData) {
		        statValues.put(aMailingSummaryData.getCategoryindex(), aMailingSummaryData.getCount());
		    }
		} else {
		    logger.error("Parameters mailingId and companyId are missing");
		}

		ObjectMapper objectMapper = new ObjectMapper();
		String jsonData = objectMapper.writeValueAsString(statValues);
		res.setContentType("application/json");
		res.setCharacterEncoding("UTF-8");
		PrintWriter writer = res.getWriter();
		writer.write(jsonData);
		// Don't close writer. It is done by the container
	} catch (Exception e) {
		logger.error("Cannot create Dashboard info", e);
	}
   }
 
Example 6
Source File: DecayRpcScheduler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public String getCallVolumeSummary() {
  try {
    ObjectMapper om = new ObjectMapper();
    return om.writeValueAsString(callCounts);
  } catch (Exception e) {
    return "Error: " + e.getMessage();
  }
}
 
Example 7
Source File: TestJackson.java    From Eagle with Apache License 2.0 5 votes vote down vote up
@Test
	public void testBase() throws JsonGenerationException, JsonMappingException, IOException {
		List<Base> objs = new ArrayList<Base>();
		ClassA a = new ClassA();
		a.setA(1);
		ClassB b = new ClassB();
		b.setB("2");
		
		objs.add(a);
		objs.add(b);
		
		ObjectMapper om = new ObjectMapper();
		om.enableDefaultTyping();
//		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		String value = om.writeValueAsString(objs);
		
		System.out.println("value = " + value);
		
		@SuppressWarnings("rawtypes")
		List result = om.readValue(value, ArrayList.class);
		System.out.println("size = " + result.size());
		Object obj1 = result.get(0);
		Object obj2 = result.get(1);
		
		Assert.assertEquals("ClassA", obj1.getClass().getSimpleName());
		Assert.assertEquals(1, ((ClassA)obj1).getA());
		Assert.assertEquals("ClassB", obj2.getClass().getSimpleName());
		Assert.assertEquals("2", ((ClassB)obj2).getB());
		
	}
 
Example 8
Source File: JsonUtil.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/** Convert a AclStatus object to a Json string. */
public static String toJsonString(final AclStatus status) {
  if (status == null) {
    return null;
  }

  final Map<String, Object> m = new TreeMap<String, Object>();
  m.put("owner", status.getOwner());
  m.put("group", status.getGroup());
  m.put("stickyBit", status.isStickyBit());

  final List<String> stringEntries = new ArrayList<>();
  for (AclEntry entry : status.getEntries()) {
    stringEntries.add(entry.toString());
  }
  m.put("entries", stringEntries);

  FsPermission perm = status.getPermission();
  if (perm != null) {
    m.put("permission", toString(perm));
    if (perm.getAclBit()) {
      m.put("aclBit", true);
    }
    if (perm.getEncryptedBit()) {
      m.put("encBit", true);
    }
  }
  final Map<String, Map<String, Object>> finalMap =
      new TreeMap<String, Map<String, Object>>();
  finalMap.put(AclStatus.class.getSimpleName(), m);

  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.writeValueAsString(finalMap);
  } catch (IOException ignored) {
  }
  return null;
}
 
Example 9
Source File: JsonUtil.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/** Convert a key-value pair to a Json string. */
public static String toJsonString(final String key, final Object value) {
  final Map<String, Object> m = new TreeMap<String, Object>();
  m.put(key, value);
  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.writeValueAsString(m);
  } catch (IOException ignored) {
  }
  return null;
}
 
Example 10
Source File: TaskConfig.java    From helix with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
  ObjectMapper mapper = new ObjectMapper();
  try {
    return mapper.writeValueAsString(this);
  } catch (IOException e) {
    LOG.error("Could not serialize TaskConfig", e);
  }
  return super.toString();
}
 
Example 11
Source File: FSImageLoader.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Return the JSON formatted FileStatus of the specified file.
 * @param path a path specifies a file
 * @return JSON formatted FileStatus
 * @throws IOException if failed to serialize fileStatus to JSON.
 */
String getFileStatus(String path) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  FsImageProto.INodeSection.INode inode = fromINodeId(lookup(path));
  return "{\"FileStatus\":\n"
      + mapper.writeValueAsString(getFileStatus(inode, false)) + "\n}\n";
}
 
Example 12
Source File: FSImageLoader.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Return the JSON formatted FileStatus of the specified file.
 * @param path a path specifies a file
 * @return JSON formatted FileStatus
 * @throws IOException if failed to serialize fileStatus to JSON.
 */
String getFileStatus(String path) throws IOException {
  ObjectMapper mapper = new ObjectMapper();
  FsImageProto.INodeSection.INode inode = fromINodeId(lookup(path));
  return "{\"FileStatus\":\n"
      + mapper.writeValueAsString(getFileStatus(inode, false)) + "\n}\n";
}
 
Example 13
Source File: TaggerServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Map<String, Integer> countCollectionsClassifiers(
		List<String> collectionCodes) throws AidrException {

	try {
		Client client = ClientBuilder.newBuilder()
				.register(JacksonFeature.class).build();
		WebTarget webResource = client.target(taggerMainUrl
				+ "/crisis/crises");

		String input = "";

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		objectMapper.configure(
				DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
				false);
		input = objectMapper.writeValueAsString(collectionCodes);
		Response clientResponse = webResource.request(
				MediaType.APPLICATION_JSON).post(Entity.json(input));
		String jsonResponse = clientResponse.readEntity(String.class);
		HashMap<String, Integer> rv = objectMapper.readValue(jsonResponse,
				HashMap.class);

		return rv;
	} catch (Exception e) {
		logger.error("Error while getting amount of classifiers by collection codes in Tagger", e);
		throw new AidrException(
				"Error while getting amount of classifiers by collection codes in Tagger",
				e);
	}
}
 
Example 14
Source File: Attribute.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
/**
 * Produces a json from a list of attributes
 *
 * @param attributeDetails List of attributes to serialize
 * @return A string representing the json
 * @throws IOException
 */
@JsonIgnore
public static String getJsonFromAttributeList(List<Attribute> attributeDetails) throws IOException {
    ObjectMapper mapper = ObjectMapperHelper.get();
    String jsonContent;
    try {
        jsonContent = mapper.writeValueAsString(attributeDetails);
    } catch (IOException e) {
        log.error("Can't process the json file: " + e.getMessage());
        throw e;
    }
    return jsonContent;
}
 
Example 15
Source File: JSONSerDe.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
/**
 * This method takes an object representing a row of data from Hive, and
 * uses the ObjectInspector to get the data for each column and serialize
 * it. This implementation deparses the row into an object that Jackson can
 * easily serialize into a JSON blob.
 */
@Override
public Writable serialize(final Object obj, final ObjectInspector oi)
		throws SerDeException {
	final Object deparsedObj = deparseRow(obj, oi);
	final ObjectMapper mapper = new ObjectMapper();
	try {
		// Let Jackson do the work of serializing the object
		return new Text(mapper.writeValueAsString(deparsedObj));
	} catch (final Exception e) {
		throw new SerDeException(e);
	}
}
 
Example 16
Source File: RepositoryImpl.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
public static String getCreateJson(RepositoryDetails repositoryDetails) throws IOException {
    ObjectMapper mapper = ObjectMapperHelper.get();
    try {
        return mapper.writeValueAsString(repositoryDetails);
    } catch (IOException e) {
        log.error("Can't process the json file: " + e.getMessage());
        log.debug("{}", e);
        throw e;
    }
}
 
Example 17
Source File: BulkV2Connection.java    From components with Apache License 2.0 4 votes vote down vote up
static String serializeToJson(Object value) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Inclusion.NON_NULL);
    mapper.setDateFormat(CalendarCodec.getDateFormat());
    return mapper.writeValueAsString(value);
}
 
Example 18
Source File: IssueService.java    From jira-rest-client with Apache License 2.0 4 votes vote down vote up
/**
 * Add one or more worklog to an issue.
 *
 * @param worklog Issue object
 * @param issue
 * @return List
 * @throws JsonParseException json parsing failed
 * @throws JsonMappingException json mapping failed
 * @throws IOException general IO exception
 */
public WorklogElement postWorklog(final WorklogElement worklog, final Issue issue) throws JsonParseException, JsonMappingException, IOException {
    
    String issueId = issue.getId();
    
    if (StringUtils.isBlank(issueId)) {
        final String key = issue.getKey();
        
        final Issue issueByKey = getIssue(key);
        
        issueId = issueByKey.getId();
        
    }
    
    ObjectMapper mapper = new ObjectMapper();
   
    //to ignore a field if its value is null
    mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    String content = mapper.writeValueAsString(worklog);
    final WorklogElement result = postWorklog(content, issueId);

    return result;
}
 
Example 19
Source File: JsonHelper.java    From gocd-git-path-material-plugin with Apache License 2.0 4 votes vote down vote up
public static String toJson(Object object) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
    return objectMapper.writeValueAsString(object);
}
 
Example 20
Source File: ZclCommandProtocolTest.java    From zigbee4java with Apache License 2.0 4 votes vote down vote up
/**
 * Tests command serialization.
 * @param command the command
 * @throws IOException if IO exception occurs.
 */
private void testSerialization(final ZclCommand command) throws IOException {
    System.out.println(command);

    final ZclCommandMessage message1 = command.toCommandMessage();

    final byte[] payload = ZclCommandProtocol.serializePayload(message1);

    final ZclCommandMessage message2 = new ZclCommandMessage();
    message2.setType(message1.getType());

    ZclCommandProtocol.deserializePayload(payload, message2);

    final ZclCommand command2 = (ZclCommand) ZclUtil.toCommand(message2);

    Assert.assertEquals("Command equality after payload ZigBee serialization", command.toString(), command2.toString());

    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    final String json = objectMapper.writeValueAsString(message1);
    System.out.println(json);
    final ZclCommandMessage message3 = objectMapper.readValue(json, ZclCommandMessage.class);

    Assert.assertEquals("Command equality after JSON serialization", message1.toString(), message3.toString());
}