本文整理汇总了Java中com.fasterxml.jackson.databind.ObjectMapper类的典型用法代码示例。如果您正苦于以下问题:Java ObjectMapper类的具体用法?Java ObjectMapper怎么用?Java ObjectMapper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ObjectMapper类属于com.fasterxml.jackson.databind包,在下文中一共展示了ObjectMapper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: convertToString
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
/**
* convert Object into String.
* @param obj Object
* @return String
*/
public static String convertToString(Object obj) {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.error("JsonProcessingException while converting Entity into string", e);
}
return null;
}
示例2: getAllEvent
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
/**
* method to get all the events
* @param id
* @return
* @throws JsonProcessingException
*/
@RabbitListener(queues = "#{getAllEventQueue.name}")
public String getAllEvent(byte[] id){
String res = "";
List<Event> events = repository.findAll();
ObjectMapper mapper = new ObjectMapper();
Log
.forContext("MemberName", "getAllEvent")
.forContext("Service", appName)
.information("RabbitMQ : getAllEvent");
try {
res = mapper.writeValueAsString(events);
} catch (JsonProcessingException e1) {
Log
.forContext("MemberName", "getAllEvent")
.forContext("Service", appName)
.error(e1,"JsonProcessingException");
}
return res;
}
示例3: call
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
@Override
public String call(String tweet) throws Exception {
ObjectMapper mapper = new ObjectMapper();
try
{
JsonNode root = mapper.readValue(tweet, JsonNode.class);
if (root.get("lang") != null &&
"en".equals(root.get("lang").textValue()))
{
if (root.get("id") != null && root.get("text") != null)
{ System.out.println("the text is ::"+root.get("text").textValue());
return root.get("text").textValue();
}
return null;
}
return null;
}
catch (IOException ex)
{
ex.printStackTrace();
}
return null;
}
示例4: getState
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
public JsonNode getState() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode state = mapper.createObjectNode();
state.put("name", this.gameClass.getSimpleName());
ArrayNode rooms = state.putArray("rooms");
for (GameRoom room : this.rooms.values()) {
rooms.add(room.getState(false));
}
ArrayNode players = state.putArray("players");
for (GamePlayer player : this.players.values()) {
players.add(player.getState());
}
return state;
}
示例5: testPassword
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
@Test
public void testPassword() throws IOException {
String tokenUrl = authUrlPrefix + "/oauth/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=password&username=" + username + "&password=" + password;
HttpHeaders headers1 = null;
//headers1 = AuthorizationUtil.basic("admin","admin");
ResponseEntity<String> response = new TestRestTemplate().postForEntity(tokenUrl, null, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap map = new ObjectMapper().readValue(response.getBody(), HashMap.class);
String accessToken = (String) map.get("access_token");
String refreshToken = (String) map.get("refresh_token");
System.out.println("Token Info:" + map.toString());
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
response = new TestRestTemplate().exchange(resourceUrl, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("secure", new ObjectMapper().readValue(response.getBody(), HashMap.class).get("content"));
refreshToken(refreshToken);
}
示例6: ok
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
@Test
public void ok() throws Exception {
String OK = "OK";
int STATUS = 200;
String generated = (String) generator.ok(OK).handle(req, res);
verify(res, times(1)).status(STATUS);
verify(res, times(1)).type(CONTENT_TYPE);
ObjectMapper om = new ObjectMapper();
RESTResult wrapper = om.readValue(generated, RESTResult.class);
assertTrue(wrapper.getSuccess());
assertEquals(OK, wrapper.getData());
assertNull(wrapper.getError());
}
示例7: jacksonMessageConverter
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
private MappingJackson2HttpMessageConverter jacksonMessageConverter() {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Hibernate4Module().enable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION));
messageConverter.setObjectMapper(mapper);
return messageConverter;
}
示例8: updatePortPairGroup
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
/**
* Update details of a specified port pair group id.
*
* @param id port pair group id
* @param stream port pair group from json
* @return 200 OK, 404 if given identifier does not exist
*/
@PUT
@Path("{group_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response updatePortPairGroup(@PathParam("group_id") String id,
final InputStream stream) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode jsonTree = (ObjectNode) mapper.readTree(stream);
JsonNode port = jsonTree.get("port_pair_group");
PortPairGroup portPairGroup = codec(PortPairGroup.class).decode((ObjectNode) port, this);
Boolean isSuccess = nullIsNotFound(get(PortPairGroupService.class).updatePortPairGroup(portPairGroup),
PORT_PAIR_GROUP_NOT_FOUND);
return Response.status(OK).entity(isSuccess.toString()).build();
} catch (IOException e) {
log.error("Update port pair group failed because of exception {}.", e.toString());
throw new IllegalArgumentException(e);
}
}
示例9: getRestTemplate
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
protected RestTemplate getRestTemplate() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new Jackson2HalModule());
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
converter.setObjectMapper(mapper);
return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}
示例10: createObjectMapper
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
private static ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Jdk8Module());
mapper.registerModule(new JavaTimeModule());
mapper.registerModule(new ParameterNamesModule());
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
return mapper;
}
示例11: arrayWithUniqueItemsProducesSet
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
@Test
public void arrayWithUniqueItemsProducesSet() {
JCodeModel codeModel = new JCodeModel();
JPackage jpackage = codeModel._package(getClass().getPackage().getName());
ObjectMapper mapper = new ObjectMapper();
ObjectNode itemsNode = mapper.createObjectNode();
itemsNode.put("type", "integer");
ObjectNode propertyNode = mapper.createObjectNode();
propertyNode.set("uniqueItems", BooleanNode.TRUE);
propertyNode.set("items", itemsNode);
JClass propertyType = rule.apply("fooBars", propertyNode, jpackage, mock(Schema.class));
assertThat(propertyType, notNullValue());
assertThat(propertyType.erasure(), is(codeModel.ref(Set.class)));
assertThat(propertyType.getTypeParameters().get(0).fullName(), is(Integer.class.getName()));
}
示例12: test_complex
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
/**
* Tests {@link Controller} serialization/deserialization.
* @throws IOException when command cannot be serialized/deserialized.
*/
@Test
public void test_complex() throws IOException, ParseException {
Controller ctrlExpected = new Controller(
"initCustom3", "cmdCustom3", "logCustom3",
new Interval(10, 15, TimeUnit.SECONDS),
10L,
new Interval(10, 15, TimeUnit.SECONDS),
new HttpProxy("192.168.0.1", 8080),
"* * * ? * SAT,SUN",
new HashMap<String,String>(){{put("User-Agent", "CustomUserAgent");}});
ObjectMapper mapper = new ControllerJsonMapper();
String jsonActual = mapper.writeValueAsString(ctrlExpected);
Controller ctrlActual = mapper.readValue(jsonActual, Controller.class);
Assert.assertEquals(ctrlExpected.getSleep(), ctrlActual.getSleep());
Assert.assertEquals(ctrlExpected, ctrlActual);
}
示例13: lesCartesToJson
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
private String lesCartesToJson(){
ObjectMapper obj = new ObjectMapper();
StringBuilder tmpJson = new StringBuilder();
tmpJson.append("lesCartes [ ");
for (Map.Entry<ETypeCarte, List<Carte>> entry : LesCartes.entrySet()) {
ETypeCarte key = entry.getKey();
List<Carte> value = entry.getValue();
tmpJson.append(key.toString()).append(" [ ");
for (Carte carte : value) {
tmpJson.append(carte.toString());
}
tmpJson.append(" ],");
}
tmpJson.append(" ]");
return tmpJson.toString();
}
示例14: createApiClient
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
protected <T> T createApiClient (Class<T> type) {
final HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
final ObjectMapper mapper = new ObjectMapper ();
final JacksonConverterFactory jacksonConverterFactory = JacksonConverterFactory.create (mapper);
final OkHttpClient httpClient = new OkHttpClient.Builder()
.addNetworkInterceptor (new FixedContentTypeInterceptor ())
.addInterceptor (logging).build ();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getApmHost ())
.addConverterFactory (jacksonConverterFactory)
.client (httpClient)
.build();
return retrofit.create(type);
}
示例15: testGenerate_Number_For_Long
import com.fasterxml.jackson.databind.ObjectMapper; //导入依赖的package包/类
@Test
public void testGenerate_Number_For_Long() throws JsonProcessingException {
UiForm ui = UiFormSchemaGenerator.get().generate(LongNumberForm.class);
String json = new ObjectMapper().writeValueAsString(ui);
Assert.assertThat(json, hasJsonPath("$.schema.properties.number.title", equalTo("Long Number")));
Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')]", hasSize(1)));
Assert.assertThat(json,
hasJsonPath("$.form[?(@.key=='number')].description", hasItem("This is a long number")));
Assert.assertThat(json,
hasJsonPath("$.form[?(@.key=='number')].placeholder", hasItem("Long Number PlaceHolder")));
Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].validationMessage",
hasItem("this is a validation msg for long value")));
Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].type", hasItem("number")));
Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].notitle", hasItem(true)));
Assert.assertThat(json, hasJsonPath("$.form[?(@.key=='number')].readonly", hasItem(true)));
}