下面列出了怎么用com.fasterxml.jackson.databind.JsonMappingException的API类实例代码及写法,或者点击链接到github查看源代码。
public static DBI18nDocument Json2DBDoc(TransCompDocFile compDoc)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
logger.info(compDoc.getDocFile().getAbsolutePath());
StringBuilder strBuilder = file2String(compDoc.getDocFile(), StandardCharsets.UTF_8);
logger.debug(strBuilder.toString());
DBI18nDocument doc = mapper.readValue(strBuilder.toString(), DBI18nDocument.class);
logger.debug("bundle doc component:" + doc.getComponent());
logger.debug("bundle doc locale:" + doc.getComponent());
doc.setProduct(compDoc.getProduct());
doc.setVersion(compDoc.getVersion());
doc.setComponent(compDoc.getComponent());
doc.setLocale(compDoc.getLocale());
return doc;
}
/**
* If Integrations get deleted we should also delete their metrics
*/
@Override
public void curate(Set<String> activeIntegrationIds) throws IOException, JsonMappingException {
//1. Loop over all RawMetrics
String json = jsonDB.getAsString(path(), new GetOptions().depth(1));
if (json != null) {
Map<String,Boolean> metricsMap = JsonUtils.reader().forType(TYPE_REFERENCE).readValue(json);
Set<String> rawIntegrationIds = metricsMap.keySet();
for (String rawIntId : rawIntegrationIds) {
if (! activeIntegrationIds.contains(rawIntId)) {
jsonDB.delete(path(rawIntId));
}
}
}
}
/**
* Determine whether to log the given exception coming from a
* {@link ObjectMapper#canDeserialize} / {@link ObjectMapper#canSerialize} check.
* @param type the class that Jackson tested for (de-)serializability
* @param cause the Jackson-thrown exception to evaluate
* (typically a {@link JsonMappingException})
* @since 4.3
*/
protected void logWarningIfNecessary(Type type, @Nullable Throwable cause) {
if (cause == null) {
return;
}
// Do not log warning for serializer not found (note: different message wording on Jackson 2.9)
boolean debugLevel = (cause instanceof JsonMappingException && cause.getMessage().startsWith("Cannot find"));
if (debugLevel ? logger.isDebugEnabled() : logger.isWarnEnabled()) {
String msg = "Failed to evaluate Jackson " + (type instanceof JavaType ? "de" : "") +
"serialization for type [" + type + "]";
if (debugLevel) {
logger.debug(msg, cause);
}
else if (logger.isDebugEnabled()) {
logger.warn(msg, cause);
}
else {
logger.warn(msg + ": " + cause);
}
}
}
public static JsonNode parseScalingHistory(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
List<String> violation_message = new ArrayList<String>();
ObjectNode result = new_mapper.createObjectNode();
result.put("valid", false);
JavaType javaType = getCollectionType(ArrayList.class, ArrayList.class, HistoryData.class);
new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
List<HistoryData> scalinghistory = (List<HistoryData>)new_mapper.readValue(jsonString, javaType);
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Locale locale = LocaleUtil.getLocale(httpServletRequest);
MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
Set<ConstraintViolation<List<HistoryData>>> set = validator.validate(scalinghistory);
if (set.size() > 0 ){
for (ConstraintViolation<List<HistoryData>> constraintViolation : set) {
violation_message.add(constraintViolation.getMessage());
}
result.set("violation_message", new_mapper.valueToTree(violation_message));
return result;
}
//additional data manipulation
String new_json = transformHistory(scalinghistory);
result.put("valid", true);
result.put("new_json", new_json);
return result;
}
private UmUserAuthResultDto performUserAuthentication(UmAuthContext authCtx, UmSubSystemAuthResultDto subSystemAuthResult,
UsernamePasswordAuthenticationToken userToken) throws JsonParseException, JsonMappingException, IOException
{
String host = authCtx.getHost();
int port = authCtx.getPort();
String userId = userToken.getName();
String pwd = (String) userToken.getCredentials();
String appid = subSystemAuthResult.getId();
String tmp = generatePwd(userId, pwd);
String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
String sign = md5(userId + tmp + timeStamp);
String token = subSystemAuthResult.getTok();
String auth = subSystemAuthResult.getAuth();
String url = String.format(
"http://%s:%s/um_service?style=6&appid=%s&id=%s&sign=%s&timeStamp=%s&token=%s&auth=%s", host, port,
appid, userId, sign, timeStamp, token, auth);
HttpHeaders headers = new HttpHeaders();
ResponseEntity<String> resp = sendGetRequestWithUrlParamMap(restTemplate, url, headers, String.class);
UmUserAuthResultDto authResult = objectMapper.readValue(resp.getBody(), UmUserAuthResultDto.class);
return authResult;
}
@Test
public void bundlesData() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper jsonMapper = ObjectMapperFactory.create();
String newJsonPolicy = "{\"auth_policies\":{\"namespace_auth\":{},\"destination_auth\":{}},\"replication_clusters\":[],\"bundles\":{\"boundaries\":[\"0x00000000\",\"0xffffffff\"]},\"backlog_quota_map\":{},\"persistence\":null,\"latency_stats_sample_rate\":{}}";
List<String> bundleSet = Lists.newArrayList();
bundleSet.add("0x00000000");
bundleSet.add("0xffffffff");
String newBundlesDataString = "{\"boundaries\":[\"0x00000000\",\"0xffffffff\"]}";
BundlesData data = jsonMapper.readValue(newBundlesDataString.getBytes(), BundlesData.class);
assertEquals(data.getBoundaries(), bundleSet);
Policies policies = jsonMapper.readValue(newJsonPolicy.getBytes(), Policies.class);
Policies expected = new Policies();
expected.bundles = data;
assertEquals(policies, expected);
}
@Test
public void shouldMergeCorrectlyAddCollection() throws JsonParseException, JsonMappingException, IOException {
String colId = UUID.randomUUID().toString();
String colId2 = UUID.randomUUID().toString();
List<Collection> base = new LinkedList<Collection>();
base.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList()));
List<Collection> working = new LinkedList<Collection>();
working.add(new Collection(colId, "collection1", false, new LinkedList<>(), Collections.emptyList()));
working.add(new Collection(colId2, "collection2", false, new LinkedList<>(), Collections.emptyList()));
CollectionDiffer collectionDiffer = new CollectionDiffer();
DiffNode diffNode = collectionDiffer.compare(working, base);
collectionDiffer.mergeDiffs(working, base, diffNode);
assertThat(base.size()).isEqualTo(2);
assertThat(base.get(0).getId()).isEqualTo(colId);
assertThat(base.get(0).getName()).isEqualTo("collection1");
assertThat(base.get(1).getId()).isEqualTo(colId2);
assertThat(base.get(1).getName()).isEqualTo("collection2");
}
@Test
public void convert() throws JsonParseException, JsonMappingException,
JsonProcessingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new GuavaModule());
Multimap<String, NavItem> navs = objectMapper.readValue(
objectMapper.treeAsTokens(objectMapper.readTree(jsonString)),
objectMapper.getTypeFactory().constructMapLikeType(
Multimap.class, String.class, NavItem.class));
logger.info(navs);
assertThat(navs.keys(), hasItems("123455", "999999"));
}
public void importJson(String jsonString) throws JsonParseException, JsonMappingException, IOException {
Objects.requireNonNull(jsonString);
// delete .kibana index
try {
client.delete(new DeleteRequest(kibanaIndexName), RequestOptions.DEFAULT);
} catch (ElasticsearchException ex) {
LOG.debug("Tried to delete kibana index " + kibanaIndexName + " but it is not exists", ex);
}
ObjectMapper mapper = new ObjectMapper();
KibanaConfigHolderDto holder = mapper.readValue(jsonString, KibanaConfigHolderDto.class);
for (KibanaConfigEntryDto dto : holder.getEntries()) {
processDto(dto);
LOG.debug("Importing {}", dto);
CreateIndexResponse response =
client.indices().create(new CreateIndexRequest(kibanaIndexName), RequestOptions.DEFAULT);
// client.prepareIndex(kibanaIndexName, dto.getType(), dto.getId())
// .setSource(dto.getSource()).get();
}
}
@Test
public void authenticationFailed() throws MessagingException, JsonParseException, JsonMappingException, IOException {
// @formatter:off
server.stubFor(post("/api/mail.send.json")
.willReturn(aResponse()
.withStatus(400)
.withBody(loadJson("/stubs/responses/authenticationFailed.json"))));
// @formatter:on
// @formatter:off
Email email = new Email()
.subject(SUBJECT)
.content(CONTENT_TEXT)
.from(FROM_ADDRESS)
.to(TO_ADDRESS_1);
// @formatter:on
MessagingException e = assertThrows(MessagingException.class, () -> {
messagingService.send(email);
}, "throws message exception");
assertThat("sendgrid exception", e.getCause(), allOf(notNullValue(), instanceOf(SendGridException.class)));
assertThat("root cause", e.getCause().getCause(), allOf(notNullValue(), instanceOf(IOException.class)));
assertThat("sendgrid message", e.getCause().getCause().getMessage(), Matchers.equalTo("Sending to SendGrid failed: (400) {\n" +
" \"errors\": [\"The provided authorization grant is invalid, expired, or revoked\"],\n" +
" \"message\": \"error\"\n" +
"}"));
}
@Test
public void testSimpleMapping() throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper m = new JsonMapperProvider().get();
assertTrue(m.canSerialize(Any.class));
Struct struct1 = Struct.newBuilder().putFields(
"some-key", Value.newBuilder().setStringValue("some-value").build()
).build();
Any source = Any.pack(struct1);
StringWriter buf = new StringWriter();
m.writer().writeValue(buf, source);
Any dest = m.reader().forType(Any.class).readValue(buf.toString());
assertEquals(source.getTypeUrl(), dest.getTypeUrl());
Struct struct2 = dest.unpack(Struct.class);
assertTrue(struct2.containsFields("some-key"));
assertEquals(
struct1.getFieldsOrThrow("some-key").getStringValue(),
struct2.getFieldsOrThrow("some-key").getStringValue()
);
}
public void annotateT2flows() throws JsonParseException, JsonMappingException, IOException {
String query = "PREFIX ro: <http://purl.org/wf4ever/ro#> " +
"" +
" SELECT ?ro ?p ?s ?name WHERE { " +
"?ro a ?x ;" +
" ?p ?s ." +
"?s ro:name ?name ." +
" FILTER REGEX(?name, \"t2flow$\") } ";
for (JsonNode binding : sparql(query)) {
System.out.print( binding.path("ro").path("value").asText());
System.out.print( binding.path("p").path("value").asText());
System.out.print( binding.path("s").path("value").asText());
System.out.println( binding.path("name").path("value").asText());
}
}
public T deserialize(byte[] value) throws JsonParseException, JsonMappingException, IOException {
if (null == value) {
return null;
}
return JsonUtil.readValue(value, type);
}
public static TaskStatusUpdateEvent fromJson(String serialized) throws IOException {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(serialized, TaskStatusUpdateEvent.class);
}
catch (JsonParseException | JsonMappingException e) {
LOGGER.log(Level.SEVERE, "Cannot deserialize object from json", e);
throw e;
}
}
/**
* If o is a proctor Payload object, then return its type as a string, otherwise return "none".
*/
public static String printPayloadType(final Object o) throws IOException, JsonGenerationException, JsonMappingException {
return Optional.ofNullable(o)
.filter(ob -> ob instanceof Payload)
.flatMap(ob -> ((Payload) ob).fetchPayloadType())
.map(p -> p.payloadTypeName)
.orElse("none");
}
@Override
@SuppressWarnings("unchecked")
public JsonSerializer<Object> createSerializer(SerializerProvider prov, JavaType origType)
throws JsonMappingException
{
for (Serializers serializers : customSerializers()) {
JsonSerializer<?> ser = serializers.findSerializer(prov.getConfig(), origType, null);
if (ser != null) {
return (JsonSerializer<Object>) ser;
}
}
throw new IllegalArgumentException("No explicitly configured serializer for " + origType);
}
@Test
public final void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
final String jsonArray = mapper.writeValueAsString(listOfDtos);
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]
final List<MyDto> asList = mapper.readValue(jsonArray, new TypeReference<List<MyDto>>() {
});
assertThat(asList.get(0), instanceOf(MyDto.class));
}
@Before
public void setup() throws URISyntaxException, JsonParseException, JsonMappingException,
IOException {
URL url = this.getClass().getResource("/cliqueConfiguration.yaml");
File configFile = new File(url.getFile());
assertThat(configFile.exists(), is(true));
OwlLoadConfigurationLoader owlLoadConfigurationLoader =
new OwlLoadConfigurationLoader(configFile);
loaderConfig = owlLoadConfigurationLoader.loadConfig();
cliqueConfiguration = loaderConfig.getCliqueConfiguration().get();
}
@Override
public JsonDeserializer<?> createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException {
if ( ctxt.getContextualType() == null || ctxt.getContextualType().containedType( 0 ) == null ) {
throw JsonMappingException.from( ctxt, "Cannot deserialize Ref<T>. Cannot find the Generic Type T." );
}
return new RefStdDeserializer( ctxt.getContextualType().containedType( 0 ) );
}
@Test
public void testGetCorsUrlPatternDefaultValue() throws JsonGenerationException, JsonMappingException, IOException {
// given
System.setProperty(Key.APPLICATION_MODE.toString(), Mode.TEST.toString());
// when
Map<String, String> configValues = new HashMap<>();
File tempConfig = createTempConfig(configValues);
Config config = new Config();
// then
assertThat(config.getCorsUrlPattern().toString(), equalTo(Pattern.compile(Default.CORS_URLPATTERN.toString()).toString()));
assertThat(tempConfig.delete(), equalTo(true));
}
@Test
public final void whenSerializingWithCustomSerializer_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException {
final Item myItem = new Item(1, "theItem", new User(2, "theUser"));
final ObjectMapper mapper = new ObjectMapper();
final SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(simpleModule);
final String serialized = mapper.writeValueAsString(myItem);
System.out.println(serialized);
}
@Override
public Response toResponse(final JsonMappingException exception) {
if (logger.isDebugEnabled()) {
logger.debug(exception.getMessage(), exception);
}
return Response.status(Response.Status.BAD_REQUEST).entity(buildErrorResponse(exception)).build();
}
@Override
public Object findInjectableValue(final Object valueId, final DeserializationContext ctxt, final BeanProperty forProperty, final Object beanInstance) throws JsonMappingException {
if ("ip_address".equals(valueId)) {
return ip;
} else if ("traits".equals(valueId)) {
return new Traits(ip);
} else if ("locales".equals(valueId)) {
return locales;
}
return null;
}
private static void prepareFSERefactorings(TestBuilder test, BigInteger flag)
throws JsonParseException, JsonMappingException, IOException {
List<Root> roots = getFSERefactorings(flag);
for (Root root : roots) {
test.project(root.repository, "master").atCommit(root.sha1)
.containsOnly(extractRefactorings(root.refactorings));
}
}
@Test
public void notObjectStart() {
JsonMappingException exception = Assertions.assertThrows(JsonMappingException.class,
() -> serializer.deserialize("[]", new TypeReference<AllPrimitives>() {
}));
assertThat(exception.getMessage()).contains("Expected to be in START_OBJECT got");
}
@Override
public void resolve(final DeserializationContext ctxt)
throws JsonMappingException {
if (defaultDeserializer instanceof ResolvableDeserializer) {
((ResolvableDeserializer) defaultDeserializer).resolve(ctxt);
}
}
@Test(expected = UnrecognizedPropertyException.class)
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
final ObjectMapper mapper = new ObjectMapper();
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
public String transformInput() throws JsonParseException, JsonMappingException, IOException{
Map<String, String> result = new HashMap<String, String>();
if (this.enable == true) {
result.put("state", "enabled");
}
else {
result.put("state", "disabled");
}
return BeanValidation.new_mapper.writeValueAsString(result);
}
@Override
protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
{
SerializerProvider provider = visitor.getProvider();
boolean useTimestamp = (provider != null) && useTimestamp(provider);
if (useTimestamp) {
super._acceptTimestampVisitor(visitor, typeHint);
} else {
JsonStringFormatVisitor v2 = visitor.expectStringFormat(typeHint);
if (v2 != null) {
v2.format(JsonValueFormat.DATE_TIME);
}
}
}
public T deserialize(byte[] value) throws JsonParseException, JsonMappingException, IOException {
if (null == value) {
return null;
}
return JsonUtil.readValue(value, type);
}