在这篇文章中,我们将带领您了解JacksonJsonParseExceptionMapper和JsonMappingExceptionMapper阴影自定义映射器的全貌,包括jackson字段映射的相
在这篇文章中,我们将带领您了解Jackson JsonParseExceptionMapper和JsonMappingExceptionMapper阴影自定义映射器的全貌,包括jackson字段映射的相关情况。同时,我们还将为您介绍有关@JsonFilter抛出“JsonMappingException:无法解析BeanPropertyFilter”、android – ProGuard – org.codehaus.jackson.map.JsonMappingException:没有为类型找到合适的构造函数、com.fasterxml.jackson.databind.JsonMappingException、com.fasterxml.jackson.databind.JsonMappingException的实例源码的知识,以帮助您更好地理解这个主题。
本文目录一览:- Jackson JsonParseExceptionMapper和JsonMappingExceptionMapper阴影自定义映射器(jackson字段映射)
- @JsonFilter抛出“JsonMappingException:无法解析BeanPropertyFilter”
- android – ProGuard – org.codehaus.jackson.map.JsonMappingException:没有为类型找到合适的构造函数
- com.fasterxml.jackson.databind.JsonMappingException
- com.fasterxml.jackson.databind.JsonMappingException的实例源码
Jackson JsonParseExceptionMapper和JsonMappingExceptionMapper阴影自定义映射器(jackson字段映射)
我的项目使用Spring Boot + Jersey 2。
我为JsonParseException创建了自定义的Jackson映射器,但没有被调用,而是使用了标准的Jackson
JsonParseExceptionMapper。
我的自定义映射器:
package com.rmn.gfc.common.providers; import ... @Provider public class JsonParseExceptionHandler implements ExceptionMapper<JsonParseException> { @Override public Response toResponse(JsonParseException exception) { return Response .status(Response.Status.BAD_REQUEST) // entity ... .build(); }}
我这样注册我的映射器:
@Componentpublic class OrderServiceResourceConfig extends ResourceConfig { public OrderServiceResourceConfig() { packages("com.rmn.gfc.common.providers"); }}
我确定映射器注册是可以的,因为此程序包中的其他自定义映射器正在工作,但是Jersey标准的JsonParseExceptionMapper遮盖了JsonParseException的映射器。
如何在实现中覆盖标准的Jackson Jackson JsonParseExceptionMapper?
答案1
小编典典我找到了适合我的解决方案。在自定义映射器上
使用javax.annotation.Priority
,以使其覆盖Jackson的默认映射器,例如:
@Provider@Priority(1)public class JsonParseExceptionHandler implements ExceptionMapper<JsonParseException> { // ...}
或,如果通过ResourceConfig注册JAX-RS组件,则可以这样指定优先级:
public class MyResourceConfig extends ResourceConfig { public MyResourceConfig() { register(JsonMappingExceptionHandler.class, 1); register(JsonParseExceptionHandler.class, 1); // ... }}
数字越小优先级越高。javax.ws.rs.Priorities
有一些预定义的优先级常量。
@JsonFilter抛出“JsonMappingException:无法解析BeanPropertyFilter”
当我不提供过滤器时,我会收到JsonMappingException异常(见下文).
背景:
我从recent StackOverflow post学到了,我可以使用@JsonFilter动态过滤bean序列化的属性.这很好.在我的域类中添加了@JsonFilter(“apiFilter”),并在我的jax-rs服务中添加了这个代码(使用CXF实现),我可以动态地过滤RESTful API返回的属性:
// shortened for brevity FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter",SimpleBeanPropertyFilter.filterOutAllExcept(filterProperties)); return mapper.filteredWriter(filters).writeValueAsstring(user);
问题是有不同的服务调用,我根本不想应用过滤器.在这些情况下,我想返回整个域类而不过滤任何属性.在我刚刚尝试返回域类的情况下,我会得到如下异常:
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not resolve BeanPropertyFilter with id 'apiFilter'; no FilterProvider configured at org.codehaus.jackson.map.ser.BeanSerializer.findFilter(BeanSerializer.java:252) at org.codehaus.jackson.map.ser.BeanSerializer.serializefieldsFiltered(BeanSerializer.java:216) at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:140)
解决方法
FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter",SimpleBeanPropertyFilter.serializeAllExcept(emptySet));
这样,当引擎查找@JsonFilter anotation中定义的“apiFilter”过滤器时,它会发现它,但它不会有任何作用(将序列化所有属性).
编辑
此外,您可以调用factory method()而不是filtersWriter():
ObjectWriter writer=null; if(aplyFilter) { FilterProvider filters = new SimpleFilterProvider().addFilter("apiFilter",SimpleBeanPropertyFilter.filterOutAllExcept(filterProperties)); writer=mapper.filteredWriter(filters); } else { writer=mapper.writer(); } return writer.writeValueAsstring(user);
我认为这最后一个解决方案是更清洁,而且更好.
android – ProGuard – org.codehaus.jackson.map.JsonMappingException:没有为类型找到合适的构造函数
我有一个基于Android的应用程序,它使用Rest服务连接到Google App Engine,该应用程序完美运行,直到它在发布之前通过ProGuard进行模糊处理.
运行混淆应用程序时LogCat中报告的错误是:
Unable to convert a [application/json,UTF-8] representation into an object of
class com.enterprisemk.android.bcw.bincollection.WasteCollectionAreasContainer
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found
for type [simple type,class
com.enterprisemk.android.bcw.bincollection.WasteCollectionAreasContainer]:
can not instantiate from JSON object (need to add/enable type information?)
我在proguard-project.txt文件中有以下内容:
-keepattributes *Annotation*,EnclosingMethod
-keep public class org.w3c.** {public private protected *;}
-dontwarn org.w3c.**
-keep public class org.joda.time.** {public private protected *;}
-dontwarn org.joda.time.**
-keep public class org.restlet.** { *; }
-dontwarn org.restlet.**
-keep public class org.codehaus.** { *; }
-dontwarn org.codehaus.**
-keepattributes Signature
-keepnames class com.fasterxml.jackson.** { *; }
-dontwarn com.fasterxml.jackson.databind.**
而我的班级错误指的是:
public class WasteCollectionAreasContainer {
public List
要在通过ProGuard进行模糊处理之前重申该应用程序可以完美运行.
任何人都可以帮我解决这个问题吗?
最佳答案
错误消息
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type
[simple type,class com.enterprisemk.android.bcw.bincollection.WasteCollectionAreasContainer]:
can not instantiate from JSON object (need to add/enable type information?)
表明Jackson库试图使用反射来反序列化你的类,它的原始名称和带注释的构造函数. ProGuard无法预见到这一点,因此它可能已删除或重命名了该类及其构造函数.您可能需要明确地保留它们:
-keep class com.enterprisemk.android.bcw.bincollection.WasteCollectionAreasContainer {
出于同样的原因,可能还需要保留其他类似的类/字段/方法.
com.fasterxml.jackson.databind.JsonMappingException
背景
- 在搭建 SSM 整合 activiti 项目时,在查找 activiti 定义的流程模板时,前台不能够接受到 ProcessDefinition 这个对象。
原因
- ProcessDefinition 是一个接口,在 Spring MVC 中使用 Jackson 将数据对象以 Json 格式传递给前台时,这个对象必须有无参构造函数,而 ProcessDefinition 没有。
解决办法
- 自己定义一个 JavaBean,将 ProcessDefinition 的值赋值给 JavaBean,将 JavaBean 以 Json 格式传递给前台。代码如下
/**
* 列出流程模板
*/
@RequestMapping(value="processlist", method = RequestMethod.GET)
public List<Process> processList() {
RepositoryService repositoryService = processEngine.getRepositoryService();
ProcessDefinitionQuery createProcessDefinitionQuery = repositoryService.createProcessDefinitionQuery();
List<ProcessDefinition> list = createProcessDefinitionQuery.list();
List<Process> processList=new ArrayList<Process>();
for (ProcessDefinition listTemp: list) {
Process process = new Process();
process.setId(listTemp.getId());
process.setName(listTemp.getName());
processList.add(process);
}
return processList;
}
Process 是自己定义的 JavaBean。
com.fasterxml.jackson.databind.JsonMappingException的实例源码
public static Echo_sol_Echo getEchoContract() throws JsonParseException,JsonMappingException,IOException,CipherException { Web3j web3j = Web3j.build(new HttpService()); logger.debug("[ETH-INFO] Connected to TestRPC"); ObjectMapper objectMapper = ObjectMapperFactory.getobjectMapper(); WalletFile walletFile = objectMapper .readValue(ContractHelper.class.getResourceAsstream("/accountKeystore.json"),WalletFile.class); Credentials credentials = Credentials.create(Wallet.decrypt(password,walletFile)); logger.debug("[ETH-INFO] Credentials: " + credentials.getAddress()); logger.debug("[ETH-INFO] Loading contract: " + contractAddress); ese = Echo_sol_Echo.load(contractAddress,web3j,credentials,GAS_PRICE,GAS_LIMIT); startObservable(); return ese; }
/** * Validate logins yml. * @param loginsYml logins yml * @return true if valid */ @PostMapping(value = "/logins/validate",consumes = {TEXT_PLAIN_VALUE}) @ApiOperation(value = "Validate uaa login properties format",response = UaaValidationVM.class) @ApiResponses(value = { @ApiResponse(code = 200,message = "Uaa validation result",response = UaaValidationVM.class),@ApiResponse(code = 500,message = "Internal server error")}) @SneakyThrows @Timed public UaaValidationVM validate(@RequestBody String loginsYml) { try { mapper.readValue(loginsYml,TenantLogins.class); return UaaValidationVM.builder().isValid(true).build(); } catch (JsonParseException | JsonMappingException e) { return UaaValidationVM.builder().isValid(false).errorMessage(e.getLocalizedMessage()).build(); } }
/** * Loads and returns the AWS Java SDK internal configuration from the classpath. */ static InternalConfig load() throws JsonParseException,IOException { // First try loading via the class by using a relative path URL url = ClassLoaderHelper.getResource(DEFAULT_CONfig_RESOURCE_RELATIVE_PATH,true,InternalConfig.class); // classesFirst=true if (url == null) { // Then try with the absolute path url = ClassLoaderHelper.getResource(DEFAULT_CONfig_RESOURCE_ABSOLUTE_PATH,InternalConfig.class); } InternalConfigJsonHelper config = loadfrom(url); InternalConfigJsonHelper configOverride; URL overrideUrl = ClassLoaderHelper.getResource("/" + CONfig_OVERRIDE_RESOURCE,InternalConfig.class); if (overrideUrl == null) { // Try without a leading "/" overrideUrl = ClassLoaderHelper.getResource(CONfig_OVERRIDE_RESOURCE,InternalConfig.class); } if (overrideUrl == null) { log.debug("Configuration override " + CONfig_OVERRIDE_RESOURCE + " not found."); configOverride = new InternalConfigJsonHelper(); } else { configOverride = loadfrom(overrideUrl); } InternalConfig merged = new InternalConfig(config,configOverride); merged.setDefaultConfigFileLocation(url); merged.setoverrideConfigFileLocation(overrideUrl); return merged; }
@PostMapping(value = "/timelines/properties/validate",consumes = {TEXT_PLAIN_VALUE}) @ApiOperation(value = "Validate timeline properties format",response = TimeLineValidationVM.class) @ApiResponses(value = { @ApiResponse(code = 200,message = "Timeline validation result",response = TimeLineValidationVM.class),message = "Internal server error")}) @SneakyThrows @Timed public TimeLineValidationVM validate(@RequestBody String timelineYml) { try { mapper.readValue(timelineYml,TenantProperties.class); return TimeLineValidationVM.builder().isValid(true).build(); } catch (JsonParseException | JsonMappingException e) { log.error("Error while validation",e); return TimeLineValidationVM.builder().isValid(false).errorMessage(e.getLocalizedMessage()).build(); } }
@Test void getBadReportDetails() throws NoSuchFieldException,illegalaccessexception,JsonProcessingException { ObjectMapper mockMapper = mock(ObjectMapper.class); when(mockMapper.writeValueAsBytes(any(AllErrors.class))) .thenThrow(new JsonMappingException("meep")); Converter converter = new Converter( new PathSource(Paths.get("../qrda-files/valid-QRDA-III-latest.xml"))); Converter.ConversionReport badReport = converter.getReport(); Field field = badReport.getClass().getDeclaredField("mapper"); field.setAccessible(true); field.set(badReport,mockMapper); assertThrows(EncodeException.class,badReport::getValidationErroRSSource); }
@Test public void testArray() throws JsonParseException,IOException { assertTrue(config.getProperty("phoneNumbers",List.class) instanceof List); final List<Map<String,String>> testList = new ArrayList<>(); Map<String,String> testMapEntry = new HashMap<>(); testMapEntry.put("type","home"); testMapEntry.put("number","212 555-1234"); testList.add(testMapEntry); testMapEntry = new HashMap<>(); testMapEntry.put("type","office"); testMapEntry.put("number","646 555-4567"); testList.add(testMapEntry); assertEquals(testList,config.getProperty("phoneNumbers",List.class)); assertEquals(new ArrayList<>(),config.getProperty("children",List.class)); }
private static Optional<JsonSchema> getSchemma(Class<?> clazz) { ObjectMapper mapper = new ObjectMapper(); Optional<JsonSchema> schema = Optional.empty(); SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); Optional<Class<?>> realClazz = ReflectionUtils.getGenericclass(clazz); boolean iterable = Iterable.class.isAssignableFrom(clazz) && realClazz.isPresent(); if (iterable) { clazz = realClazz.get(); } try { mapper.acceptJsonFormatVisitor(clazz,visitor); JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper); schema = Optional.ofNullable(schemaGen.generateSchema(clazz)); if (iterable) { // Todo: decirle que es una collection } } catch (JsonMappingException e) { LOGGER.error("Se produjo un error al crear el JsonSchemma para la clase {}",clazz.getSimpleName(),e); } return schema; }
private List<String> getAPIKeyList() throws ServerError,JsonParseException,IOException{ List<String> list = new ArrayList<String>(); String accountListUrlPath = props.getProperty("application-list-url-path"); accountListUrlPath=accountListUrlPath.replaceAll("<token>",props.getProperty("acccess-token")); accountListUrlPath=accountListUrlPath.replaceAll("<serviceid>",props.getProperty("service-id-a")); //String body = props.getProperty("tempbody"); String body = apiAccessor.get(HOST+accountListUrlPath).getBody(); while ( body.indexOf("user_key")!=-1){ int indexOfStartOfKey = body.indexOf("user_key") + 11; int indexOfEndOfKey = indexOfStartOfKey+32; String apiKey = body.substring(indexOfStartOfKey,indexOfEndOfKey); list.add(apiKey); body = body.substring(indexOfEndOfKey); } return list; }
public static QueryObjectProvider fromJsonNode(CatalogService catalogService,VirtualObjectService virtualObjectService,PlatformServer server,JsonNode fullQuery,Integer rid,PackageMetaData packageMetaData) throws JsonParseException,QueryException { if (fullQuery instanceof ObjectNode) { JsonQueryObjectModelConverter converter = new JsonQueryObjectModelConverter(packageMetaData); Query query = converter.parseJson("query",(ObjectNode) fullQuery); return new QueryObjectProvider(catalogService,virtualObjectService,server,query,rid,packageMetaData); } else { throw new QueryException("Query root must be of type object"); } }
@StreamListener(target = Sink.INPUT,condition="payload.messageType.toString()=='FetchGoodsCommand'") @Transactional public void retrievePaymentCommandReceived(String messageJson) throws JsonParseException,IOException { Message<FetchGoodsCommandPayload> message = new ObjectMapper().readValue(messageJson,new TypeReference<Message<FetchGoodsCommandPayload>>(){}); FetchGoodsCommandPayload fetchGoodsCommand = message.getPayload(); String pickId = inventoryService.pickItems( // fetchGoodsCommand.getItems(),fetchGoodsCommand.getReason(),fetchGoodsCommand.getRefId()); messageSender.send( // new Message<GoodsFetchedEventPayload>( // "GoodsFetchedEvent",// message.getTraceId(),// new GoodsFetchedEventPayload() // .setRefId(fetchGoodsCommand.getRefId()) .setPickId(pickId))); }
/** * A callback so a JsonGenerator can be used inline but exception are handled here * @param outStream OutputStream * @param writer The writer interface * @throws IOException */ public void withWriter(OutputStream outStream,Writer writer) throws IOException { try { JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(outStream,encoding); writer.writeContents(generator,objectMapper); } catch (JsonMappingException error) { logger.error("Failed to write Json output",error); } catch (JsonGenerationException generror) { logger.error("Failed to write Json output",generror); } }
private void assertForbidden(final String path) throws IOException,ClientProtocolException,JsonMappingException { final HttpDelete httpdelete = new HttpDelete(BASE_URI + RESOURCE + path); HttpResponse response = null; try { response = httpclient.execute(httpdelete); Assert.assertEquals(HttpStatus.SC_FORBIDDEN,response.getStatusLine().getStatusCode()); final String content = IoUtils.toString(response.getEntity().getContent(),StandardCharsets.UTF_8); final Map<?,?> result = new ObjectMapperTrim().readValue(content,HashMap.class); Assert.assertEquals("security",result.get("code")); Assert.assertNull(result.get("cause")); Assert.assertNull(result.get("message")); } finally { if (response != null) { response.getEntity().getContent().close(); } } }
@Override public <T> Document asDocumentInternal(T object) { ObjectMapper objectMapper = getobjectMapper(); try { JsonNode node = objectMapper.convertValue(object,JsonNode.class); return loadDocument(node); } catch (IllegalArgumentException iae) { log.error("Error while converting object to document ",iae); if (iae.getCause() instanceof JsonMappingException) { JsonMappingException jme = (JsonMappingException) iae.getCause(); if (jme.getCause() instanceof StackOverflowError) { throw new ObjectMappingException(errorMessage( "cyclic reference detected. " + jme.getPathReference(),OME_CYCLE_DETECTED)); } } throw iae; } }
@StreamListener(target = Sink.INPUT,condition="payload.messageType.toString()=='RetrievePaymentCommand'") @Transactional public void retrievePaymentCommandReceived(String messageJson) throws JsonParseException,IOException { Message<RetrievePaymentCommandPayload> message = new ObjectMapper().readValue(messageJson,new TypeReference<Message<RetrievePaymentCommandPayload>>(){}); RetrievePaymentCommandPayload retrievePaymentCommand = message.getPayload(); System.out.println("Retrieve payment: " + retrievePaymentCommand.getAmount() + " for " + retrievePaymentCommand.getRefId()); camunda.getRuntimeService().createMessageCorrelation(message.getMessageType()) // .processInstanceBusinessKey(message.getTraceId()) .setvariable("amount",retrievePaymentCommand.getAmount()) // .setvariable("remainingAmount",retrievePaymentCommand.getAmount()) // .setvariable("refId",retrievePaymentCommand.getRefId()) // .correlateWithResult(); }
@Test public void shouldSerializeSimpleResponseBody() throws JsonParseException,IOException { UserRequestTest request = new UserRequestTest("user name","user address"); ResponseEntity response = ResponseEntity.of(request); Assert.assertEquals(HttpStatus.SC_OK,response.getStatusCode()); Assert.assertNotNull(response.getBody()); //should be able to deserialize UserRequestTest deserialized = new ObjectMapper().readValue(response.getBody(),UserRequestTest.class); Assert.assertNotNull(request); Assert.assertEquals(request.getName(),deserialized.getName()); Assert.assertEquals(request.getAddress(),deserialized.getAddress()); Assert.assertNull(response.getHeaders()); }
@CsapDoc ( notes = { "Summary status of host" },linkTests = "default" ) @RequestMapping ( { "/status" } ) public ObjectNode status () throws JsonGenerationException,IOException { ObjectNode healthJson = jacksonMapper.createObjectNode(); if ( Application.isJvmInManagerMode() ) { healthJson.put( "error","vmHealth is only enabled on CsAgent urls." ); } else { healthJson = csapApp.statusForAdminorAgent( ServiceAlertsEnum.ALERT_LEVEL ); } return healthJson; }
@SuppressWarnings({ "unchecked" }) @Test public void serializetest() throws JsonParseException,IOException { List<WampRole> roles = createRoles(); WelcomeMessage welcomeMessage = new WelcomeMessage(9129137332L,roles,"realm"); assertthat(welcomeMessage.getCode()).isEqualTo(2); assertthat(welcomeMessage.getSessionId()).isEqualTo(9129137332L); assertthat(welcomeMessage.getRoles()).isEqualTo(roles); String json = serializetoJson(welcomeMessage); String expected = "[2,9129137332,{\"roles\":{\"dealer\":{\"features\":{\"caller_identification\":true}},\"broker\":{\"features\":{\"subscriber_blackwhite_listing\":true,\"publisher_exclusion\":true,\"publisher_identification\":true,\"pattern_based_subscription\":true}}},\"realm\":\"realm\"}]"; ObjectMapper om = new ObjectMapper(); assertthat(om.readValue(json,List.class)) .isEqualTo(om.readValue(expected,List.class)); }
/** * Main API call method. Takes in a {@link HttpUriRequest} comprising of a * URI and method * * @param request * with the relevant URI and method (with associated data is * appropriate) * @param type * what the response should interpreted as * @param login * whether this is a call specifically to login * @return the type requested * @throws IOException * if it's not possible to get a valid response from the API * @throws GroupsIOApiException * if the API returns an error,or an error is experienced * during deserialisation */ protected <T> T callApi(final HttpUriRequest request,final Class<T> type,final Boolean login) throws IOException,GroupsIOApiException { try (final CloseableHttpClient client = getHttpClient(login,request)) { final HttpResponse response = client.execute(request); final InputStream stream = response.getEntity().getContent(); final byte[] bytes = IoUtils.toByteArray(stream); if (response.getStatusLine().getStatusCode() != 200) { throw new GroupsIOApiException(mapToError(bytes)); } try { return type.cast(OM.readValue(bytes,Class.forName(type.getName()))); } catch (final JsonMappingException | ClassNotFoundException jme) { throw new GroupsIOApiException(mapToError(bytes)); } } }
@Test public void testNullInComment() throws IOException { final Comment aComment = new Comment(); aComment.setContent(null); ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out,new Writer() { @Override public void writeContents(JsonGenerator generator,ObjectMapper objectMapper) throws JsonGenerationException,IOException { FilterProvider fp = new SimpleFilterProvider().addFilter( JacksonHelper.DEFAULT_FILTER_NAME,new ReturnAllBeanProperties()); objectMapper.writer(fp).writeValue(generator,aComment); } }); assertEquals("Null values should not be output.","{\"canEdit\":false,\"canDelete\":false}",out.toString()); }
@SuppressWarnings({"rawtypes","unchecked"}) @Test public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException,IOException { ResponseEntity<String> response = new TestRestTemplate("trusted-app","secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password",null,String.class); String responseText = response.getBody(); assertEquals(HttpStatus.OK,response.getStatusCode()); HashMap jwtMap = new ObjectMapper().readValue(responseText,HashMap.class); assertEquals("bearer",jwtMap.get("token_type")); assertEquals("read write",jwtMap.get("scope")); assertTrue(jwtMap.containsKey("access_token")); assertTrue(jwtMap.containsKey("expires_in")); assertTrue(jwtMap.containsKey("jti")); String accesstoken = (String) jwtMap.get("access_token"); Jwt jwtToken = JwtHelper.decode(accesstoken); String claims = jwtToken.getClaims(); HashMap claimsMap = new ObjectMapper().readValue(claims,HashMap.class); assertEquals("spring-boot-application",((List<String>) claimsMap.get("aud")).get(0)); assertEquals("trusted-app",claimsMap.get("client_id")); assertEquals("admin",claimsMap.get("user_name")); assertEquals("read",((List<String>) claimsMap.get("scope")).get(0)); assertEquals("write",((List<String>) claimsMap.get("scope")).get(1)); assertEquals("ROLE_ADMIN",((List<String>) claimsMap.get("authorities")).get(0)); }
@Test public void accessprotectedResourceByJwtTokenForAdmin() throws JsonParseException,IOException { ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/admin",String.class); assertEquals(HttpStatus.UNAUTHORIZED,response.getStatusCode()); response = new TestRestTemplate("trusted-app",HashMap.class); String accesstoken = (String) jwtMap.get("access_token"); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization","Bearer " + accesstoken); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/admin",HttpMethod.GET,new httpentity<>(null,headers),String.class); assertEquals(HttpStatus.OK,response.getStatusCode()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal",String.class); assertEquals("admin",response.getBody()); response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles",String.class); assertEquals("[{\"authority\":\"ROLE_ADMIN\"}]",response.getBody()); }
@PostMapping(value = "/uaa/properties/validate",consumes = {TEXT_PLAIN_VALUE}) @ApiOperation(value = "Validate uaa properties format",message = "Internal server error")}) @SneakyThrows @Timed public UaaValidationVM validate(@RequestBody String timelineYml) { try { mapper.readValue(timelineYml,TenantProperties.class); return UaaValidationVM.builder().isValid(true).build(); } catch (JsonParseException | JsonMappingException e) { return UaaValidationVM.builder().isValid(false).errorMessage(e.getLocalizedMessage()).build(); } }
@Test @SuppressWarnings("unchecked") public void intEnumIsDeserializedCorrectly() throws ClassNotFoundException,NoSuchMethodException,InvocationTargetException,IOException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/integerEnumToSerialize.json","com.example"); // the schema for a valid instance Class<?> typeWithEnumProperty = resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize"); Class<Enum> enumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.enums.IntegerEnumToSerialize$TestEnum"); // read the instance into the type ObjectMapper objectMapper = new ObjectMapper(); Object valueWithEnumProperty = objectMapper.readValue("{\"testEnum\" : 2}",typeWithEnumProperty); Method getEnumMethod = typeWithEnumProperty.getDeclaredMethod("getTestEnum"); Method getValueMethod = enumClass.getDeclaredMethod("value"); // call getTestEnum on the value assertthat(getEnumMethod,is(notNullValue())); Object enumObject = getEnumMethod.invoke(valueWithEnumProperty); // assert that the object returned is a) a TestEnum,and b) calling .value() on it returns 2 // as per the json snippet above assertthat(enumObject,isinstanceOf.instanceOf(enumClass)); assertthat(getValueMethod,is(notNullValue())); assertthat((Integer)getValueMethod.invoke(enumObject),is(2)); }
@DataProvider(name = "multiplePolicySetsRequestDataProvider") private Object[][] multiplePolicySetsRequestDataProvider() throws JsonParseException,IOException { List<PolicySet> denyPolicySet = createDenyPolicySet(); List<PolicySet> notApplicableAndDenyPolicySets = createNotApplicableAndDenyPolicySets(); return new Object[][] { requestEvaluationWithEmptyPolicySetsListAndEmptyPriorityList(),requestEvaluationWithOnePolicySetAndEmptyPriorityList(denyPolicySet),requestEvaluationWithFirstOfOnePolicySets(denyPolicySet),requestEvaluationWithFirstOfTwoPolicySets(notApplicableAndDenyPolicySets),requestEvaluationWithSecondOfTwoPolicySets(notApplicableAndDenyPolicySets),requestEvaluationWithAllOfTwoPolicySets(notApplicableAndDenyPolicySets) }; }
@Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor,JavaType typeHint) throws JsonMappingException { if (visitor != null) { visitor.expectStringFormat(typeHint); } }
private String writeResponse(final Object respons) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); jsonHelper.withWriter(out,IOException { objectMapper.writeValue(generator,respons); } }); System.out.println(out.toString()); return out.toString(); }
@SuppressWarnings("unchecked") public String generate(Client client,Card card,String encryptionKey) throws JsonParseException,NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeyException,InvalidKeySpecException,IllegalBlockSizeException,BadPaddingException,CertificateException{ String encrypted; //pegando publickey List<NameValuePair> encReq = new ArrayList<>(); encReq.add(new BasicNameValuePair("encryption_key",encryptionKey)); CardHashKey gen = client.get(encReq,CardHashKey.class); //criando queryString List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("card_number",card.getCardNumber())); params.add(new BasicNameValuePair("card_holder_name",card.getHolderName())); params.add(new BasicNameValuePair("card_expiration_date",card.getExpirationDate())); params.add(new BasicNameValuePair("card_cvv",card.getCvv())); String queryString = URLEncodedUtils.format(params,"UTF-8"); String publickey = gen.getPublicKey(); publickey = publickey.replaceAll("-----BEGIN PUBLIC KEY-----",""); publickey = publickey.replaceAll("-----END PUBLIC KEY-----",""); //criptografando;; BASE64Decoder b64 = new BASE64Decoder(); byte[] decoded = b64.decodeBuffer(publickey); X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(spec); cipher.init(Cipher.ENCRYPT_MODE,key); //toBase64 encrypted = Base64.getEncoder().encodetoString(cipher.doFinal(queryString.getBytes())); return String.valueOf(gen.getId()).concat("_").concat(encrypted); }
@SuppressWarnings("unchecked") @Test public void validateConfiguredParameters_createJsonError() throws Exception { // given prepareServiceAccessible(true); model.setServiceParameters(new ArrayList<PricedParameterRow>()); bean.setJsonValidator(new JsonParameterValidator(bean .getJsonConverter())); addPricedParameterRow("ABoolean",ParameterValueType.BOOLEAN,false); model.setParameterConfigResponse(CONfig_RESPONSE_ERROR); JsonObject configRequest = givenConfigRequest(); addJsonParameter(configRequest,"ABoolean","false",false); doReturn(configRequest).when(jsonConverter) .getServiceParametersAsJsonObject(Matchers.any(List.class),Matchers.anyBoolean(),Matchers.anyBoolean()); doThrow(new JsonMappingException("Error in json mapping")).when( jsonConverter).createJsonString(Matchers.any(JsonObject.class)); // when String outcome = bean.getJsonValidator().validateConfiguredParameters( bean.getModel()); // then assertEquals("Outcome error expected: Rerender parent page",SubscriptionDetailsCtrlConstants.OUTCOME_ERROR,outcome); assertTrue("Error expected in validation result",model .getParameterValidationResult().getValidationError()); assertNull("No config request expected in validation result",model .getParameterValidationResult().getConfigRequest()); }
@Override public Response toResponse(JsonMappingException exception) { if(exception instanceof UnrecognizedPropertyException) { return buildresponse(BAD_REQUEST,"Unrecognized property.",Collections.singletonMap("property_name",((UnrecognizedPropertyException) exception).getPropertyName())); } return buildresponse(BAD_REQUEST,"Mapping error - Some fields are missing."); }
public static UpgradeProcessorsConfig newInstance(Path configFilePath) throws JsonParseException,IOException { JacksonXmlModule module = new JacksonXmlModule(); module.setDefaultUseWrapper(false); XmlMapper xmlMapper = new XmlMapper(module); return xmlMapper.readValue(configFilePath.toFile(),UpgradeProcessorsConfig.class); }
@Test public void blowsUpIfPassWordsFileIsMalformed() throws Exception { File tempFile = temporaryFolder.newFile("passwords.yml"); FileWriter fileWriter = new FileWriter(tempFile); fileWriter.write("invalid content"); fileWriter.flush(); assertthatThrownBy(() -> passwordsUnmarshaller.parsePasswords(tempFile)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage(format("Error occurred reading passwords file '%s'",tempFile.getName())) .hasCauseExactlyInstanceOf(JsonMappingException.class); }
@Test public void getInvalidDate() throws Exception { try { client.datetimerfc1123s().getInvalid(); Assert.assertTrue(false); } catch (Exception exception) { // expected Assert.assertEquals(JsonMappingException.class,exception.getCause().getClass()); } }
@Test public void shouldFailToDeserializeIfNumwantIsNotDefined() throws IOException { final String jsonWithoutNumwant = validJSON.replaceAll("\"numwant\":[ ]*[0-9]+,",""); assertthatThrownBy(() -> mapper.readValue(jsonWithoutNumwant,BitTorrentClientConfig.class)) .isinstanceOf(JsonMappingException.class) .hasMessageContaining("Missing required creator property 'numwant'"); }
@Override public Response toResponse(JsonMappingException e) { return Response .status(Response.Status.BAD_REQUEST) .entity(JsonError.builder() .code(Response.Status.BAD_REQUEST.getStatusCode()) .message("Unable to map request JSON") .build()) .type(MediaType.APPLICATION_JSON) .build(); }
@ExceptionHandler(value = {ServiceException.class,JsonMappingException.class}) protected ResponseEntity<Object> handleServiceException(Exception ex,WebRequest request) { ex.printstacktrace(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(ex,new HttpErrorServer(ex.getLocalizedMessage()),headers,HttpStatus.INTERNAL_SERVER_ERROR,request); }
@Test(dataProvider = "policyDataProvider") public void testEvaluateWithPolicyWithCacheSetException(final File inputPolicy,final Effect effect) throws JsonParseException,IOException { Mockito.doThrow(new RuntimeException()).when(this.cache) .set(Mockito.any(PolicyEvaluationRequestCacheKey.class),Mockito.any(PolicyEvaluationResult.class)); testEvaluateWithPolicy(inputPolicy,effect); }
public static MultiThreadQueryObjectProvider fromJsonString(ThreadPoolTaskExecutor executor,CatalogService catalogService,String json,PackageMetaData packageMetaData) throws JsonParseException,QueryException { return fromJsonNode(executor,catalogService,OBJECT_MAPPER.readValue(json,ObjectNode.class),packageMetaData); }
@Test public void canGenerateJSON() throws JsonParseException,IOException { // Exclusive lock LockInfoImpl lockInfo = new LockInfoImpl(); lockInfo.setExclusiveLockToken("opaque-lock-token"); lockInfo.setDepth(WebDAV.INFINITY); lockInfo.setScope(WebDAV.XML_EXCLUSIVE); String json = lockInfo.toJSON(); ObjectMapper objectMapper = new ObjectMapper(); assertTrue("ADDINFO_WEBDAV_MARKER",json.startsWith(LockInfoImpl.ADDINFO_WEBDAV_MARKER)); json = json.substring(LockInfoImpl.ADDINFO_WEBDAV_MARKER.length() + 1); LockInfoImpl parsed = objectMapper.readValue(json,LockInfoImpl.class); assertEquals("opaque-lock-token",parsed.getExclusiveLockToken()); assertEquals(WebDAV.INFINITY,parsed.getDepth()); assertEquals(WebDAV.XML_EXCLUSIVE,parsed.getScope()); // Shared lock lockInfo = new LockInfoImpl(); lockInfo.addSharedLockToken("opaque-lock-token-1"); lockInfo.addSharedLockToken("opaque-lock-token-2"); lockInfo.addSharedLockToken("opaque-lock-token-3"); lockInfo.setDepth(WebDAV.ZERO); lockInfo.setScope(WebDAV.XML_SHARED); json = lockInfo.toJSON(); assertTrue("ADDINFO_WEBDAV_MARKER",json.startsWith(LockInfoImpl.ADDINFO_WEBDAV_MARKER)); json = json.substring(LockInfoImpl.ADDINFO_WEBDAV_MARKER.length() + 1); parsed = objectMapper.readValue(json,LockInfoImpl.class); Set<String> sortedTokens = new TreeSet<String>(parsed.getSharedLockTokens()); Iterator<String> tokenIt = sortedTokens.iterator(); assertEquals("opaque-lock-token-1",tokenIt.next()); assertEquals("opaque-lock-token-2",tokenIt.next()); assertEquals("opaque-lock-token-3",tokenIt.next()); assertEquals(WebDAV.ZERO,parsed.getDepth()); assertEquals(WebDAV.XML_SHARED,parsed.getScope()); }
/** * Method to update a review with RabbitMQ * @return * @throws IOException * @throws JsonMappingException * @throws JsonParseException */ @RequestMapping(value = "/updateReview",method = RequestMethod.POST) public String updateReview(@RequestParam Map<String,String> body) throws JsonParseException,IOException{ Log .forContext("person",body.get("review")) .forContext("MemberName","updateReview") .forContext("Service",appName) .information("Request : updateReview"); return new RabbitClient(EXCHANGE).rabbitRPCRoutingKeyExchange(body.get("review").getBytes(ENCODE),"updateReview"); }
private HttpResponseMetaData getResponseMetaData(ClientResponseContext responseContext) throws IOException { Map<String,String> headers = FormatUtil.MultiMapAsstringMap(responseContext.getHeaders()); HttpResponseMetaData.HttpResponseMetaDataBuilder builder = HttpResponseMetaData.builder() .status(responseContext.getStatus()) .headers(headers); if (responseContext.hasEntity()) { String body; // setUp the "real" error message try (BufferedReader buffer = new BufferedReader(new InputStreamReader(responseContext.getEntityStream(),"UTF-8"))) { body = buffer.lines().collect(Collectors.joining("\n")); } try { ProblemResponse problem = mapper.readValue(body,ProblemResponse.class); if (problemwasparsed(problem)) { builder.problemResponse(problem) .incidentReferenceId(problem.incidentReferenceId); } } catch (JsonParseException | JsonMappingException e) { //ignore } if (builder.build().problemResponse == null) { builder.response(body); } } return builder.build(); }
关于Jackson JsonParseExceptionMapper和JsonMappingExceptionMapper阴影自定义映射器和jackson字段映射的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于@JsonFilter抛出“JsonMappingException:无法解析BeanPropertyFilter”、android – ProGuard – org.codehaus.jackson.map.JsonMappingException:没有为类型找到合适的构造函数、com.fasterxml.jackson.databind.JsonMappingException、com.fasterxml.jackson.databind.JsonMappingException的实例源码的相关信息,请在本站寻找。
本文标签: