下面列出了怎么用com.fasterxml.jackson.core.JsonParseException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Map<String, Integer> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
if (p.currentToken() == JsonToken.VALUE_NULL) {
return null;
}
if (p.currentToken() != JsonToken.START_ARRAY) {
throw new JsonParseException(p, "Expected start of array");
}
p.nextToken();
if (p.currentToken() == JsonToken.END_ARRAY) {
return new HashMap<> ();
}
final Map<String, Integer> result = new HashMap<>();
final Iterator<Mapping> i = p.readValuesAs(Mapping.class);
i.forEachRemaining(m -> result.put(m.getName(), m.getPort()));
return result;
}
private void checkDefinitions() throws IOException, JsonParseException, JsonMappingException {
Path yamlFile = getDefinitionPath();
List<TemplateRecordConfiguration> definitions = readDefinitions(yamlFile);
TemplateRecordConfiguration record = assertNamedRecord(definitions);
assertTrue(record.isRepeat());
assertNull(record.getMinimalRepeat());
assertEquals(
ImmutableList.of("Paragraph:nth-of-type(2)", "Paragraph:nth-of-type(3)"),
record.getCoveredPaths());
assertDefaultRecord(definitions);
Files.delete(yamlFile);
}
@RequestMapping(path = "/findAllTableRow", method = { RequestMethod.GET, RequestMethod.POST })
public @JsonIgnore Map<String, Object> findAllTableRow(@RequestBody SysDbmsTabsColsInfoVo vo) throws JsonParseException, JsonMappingException, IOException {
logger.info("findAllTableRow", ZhcxController.class);
Map<String, Object> map = new HashMap<>();
if ("oracle".equals(vo.getDbType()) || "mysql".equals(vo.getDbType())) {
// if ("单表多条件查询".equals(vo.getType())) {
// map = zhcxService.findAllSigleTableByMulteityParam(vo);
// } else if ("一键查询单表多个不同索引拼接".equals(vo.getType()) || "单表多条件更多查询".equals(vo.getType())) {
// 一键查询单表多个不同索引拼接
map = zhcxService.findBySingleTableByGroupsAndMulteityParam(vo);
// }
} else if ("elastic".equals(vo.getDbType())) {
// // elasticsearch
// map = zhcxService.findByElasticsearchByGroupsAndMulteityParam(vo);
}
return map;
}
@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"));
}
@Test
public void simpleEmail() throws MessagingException, JsonParseException, JsonMappingException, IOException {
// @formatter:off
server.stubFor(post("/v3/mail/send")
.willReturn(aResponse().withStatus(202)));
// @formatter:on
// @formatter:off
Email email = new Email()
.subject(SUBJECT)
.content(CONTENT_TEXT)
.from(FROM_ADDRESS)
.to(TO_ADDRESS_1);
// @formatter:on
messagingService.send(email);
// @formatter:off
server.verify(postRequestedFor(urlEqualTo("/v3/mail/send"))
.withRequestBody(equalToJson(resourceAsString("/expected/requests/simpleEmail.json"), true, true)));
// @formatter:on
}
@Test
public void testFullFormatRejected() throws JsonParseException, IOException, SailfishURIException {
IMessage message = generate();
message.getMetaData().setRejectReason("Test reject");
String json = JsonMessageConverter.toJson(message, false);
IMessage actual = JsonMessageConverter.fromJson(json, false);
compare(message, actual, 43, 0, 0);
Assert.assertEquals("Test reject", actual.getMetaData().getRejectReason());
Assert.assertTrue(actual.getMetaData().isRejected());
json = JsonMessageConverter.toJson(message, dictionary, false);
actual = JsonMessageConverter.fromJson(json, manager, false);
compare(message, actual, 43, 0, 0);
Assert.assertEquals("Test reject", actual.getMetaData().getRejectReason());
Assert.assertTrue(actual.getMetaData().isRejected());
}
private OrderItem getOrderItem(JsonParser parser) throws JsonParseException, IOException {
OrderItem item = new OrderItem();
if ( parser.getCurrentToken() != JsonToken.START_OBJECT ) {
throw new IllegalStateException("nextValue should have been START_OBJECT but is:[" + parser.getCurrentToken() + "]");
}
while ( parser.nextValue() != null ) {
if ( "productId".equals(parser.getCurrentName()) ) {
item.setProductId( parser.getText() );
} else if ( "quantity".equals(parser.getCurrentName()) ) {
item.setQuantity( parser.getIntValue() );
} else if ( "itemCostUSD".equals(parser.getCurrentName()) ) {
item.setItemCostUSD( parser.getFloatValue() );
}
if ( parser.getCurrentToken() == JsonToken.END_OBJECT ) {
return item;
}
}
return null;
}
@Test
public void shouldMergeCorrectlyRenameCollection() throws JsonParseException, JsonMappingException, IOException {
String colId = 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, "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(1);
assertThat(base.get(0).getId()).isEqualTo(colId);
assertThat(base.get(0).getName()).isEqualTo("collection2");
}
@Override
protected void buildBuffered(final JsonParser jp) throws IOException {
JsonToken jt;
while((jt = jp.nextToken()) != JsonToken.END_OBJECT) {
if(jt != JsonToken.FIELD_NAME)
throw new JsonParseException(jp, "Expecting field name, got " + jt.name(),
jp.getCurrentLocation());
final String fieldName = jp.getCurrentName();
final JsonValue value = new JsonValue(jp);
synchronized(this) {
properties.put(fieldName, value);
notifyAll();
}
value.buildInThisThread();
}
}
@Override
public Object get(ChannelHandlerContext ctx, URIDecoder uriDecoder) {
if (uriDecoder.contentType == null || !uriDecoder.contentType.contains(expectedContentType)) {
throw new RuntimeException("Unexpected content type. Expecting " + expectedContentType + ".");
}
switch (expectedContentType) {
case MediaType.APPLICATION_JSON :
String data = "";
try {
data = uriDecoder.getContentAsString();
return JsonParser.MAPPER.readValue(data, type);
} catch (JsonParseException | JsonMappingException jsonParseError) {
log.debug("Error parsing body param : '{}'.", data);
throw new RuntimeException("Error parsing body param. " + data);
} catch (Exception e) {
log.error("Unexpected error during parsing body param.", e);
throw new RuntimeException("Unexpected error during parsing body param.", e);
}
default :
return uriDecoder.getContentAsString();
}
}
private TransactionResultEntity readResponse(final InputStream inputStream) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamUtils.copy(inputStream, bos);
String responseMessage = null;
try {
responseMessage = new String(bos.toByteArray(), StandardCharsets.UTF_8);
logger.debug("readResponse responseMessage={}", responseMessage);
final ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(responseMessage, TransactionResultEntity.class);
} catch (JsonParseException | JsonMappingException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to parse JSON.", e);
}
final TransactionResultEntity entity = new TransactionResultEntity();
entity.setResponseCode(ResponseCode.ABORT.getCode());
entity.setMessage(responseMessage);
return entity;
}
}
private ManagedUser hbaseRowToUser(Result result) throws JsonParseException, JsonMappingException, IOException {
if (null == result || result.isEmpty())
return null;
String username = Bytes.toString(result.getRow());
byte[] valueBytes = result.getValue(Bytes.toBytes(AclConstant.USER_AUTHORITY_FAMILY),
Bytes.toBytes(AclConstant.USER_AUTHORITY_COLUMN));
UserGrantedAuthority[] deserialized = ugaSerializer.deserialize(valueBytes);
String password = "";
List<UserGrantedAuthority> authorities = Collections.emptyList();
// password is stored at [0] of authorities for backward compatibility
if (deserialized != null) {
if (deserialized.length > 0 && deserialized[0].getAuthority().startsWith(AclConstant.PWD_PREFIX)) {
password = deserialized[0].getAuthority().substring(AclConstant.PWD_PREFIX.length());
authorities = Arrays.asList(deserialized).subList(1, deserialized.length);
} else {
authorities = Arrays.asList(deserialized);
}
}
return new ManagedUser(username, password, false, authorities);
}
public static int fromJsonToWkid(JsonParser parser)
throws JsonParseException, IOException {
int wkid = 0;
if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
return 0;
}
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = parser.getCurrentName();
if ("wkid".equals(fieldName)) {
parser.nextToken();
wkid = parser.getIntValue();
}
}
return wkid;
}
public JType generatePojoFromSchema(JCodeModel codeModel, String className, String packageName, String json, String url, SourceType sourceType) throws IOException {
try {
SchemaMapper schemaMapper = new SchemaMapper(getRuleFactory(sourceType, codeGenConfig), new SchemaGenerator());
if (SourceType.JSON == sourceType) {
return schemaMapper.generate(codeModel, className, packageName, json);
} else {
URI uri;
if (url == null) {
File tmpFile = File.createTempFile("tmp", "json");
try (FileWriter writer = new FileWriter(tmpFile)) {
writer.write(json);
}
uri = tmpFile.toURI();
} else {
uri = URI.create(url);
}
return schemaMapper.generate(codeModel, className, packageName, json, uri);
}
} catch (JsonParseException e) {
logger.info("Can not generate " + className + " from schema since : " + e.getMessage());
return codeModel.ref(String.class);
}
}
@Test
public void accessProtectedResourceByJwtToken() throws JsonParseException, JsonMappingException, IOException, InvalidJwtException {
ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/client", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
String accessToken = (String) jwtMap.get("access_token");
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + accessToken);
JwtContext jwtContext = jwtConsumer.process(accessToken);
logJWTClaims(jwtContext);
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals("trusted-app", response.getBody());
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/trusted_client", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
assertEquals("[{\"authority\":\"ROLE_TRUSTED_CLIENT\"}]", response.getBody());
}
@Test
public void unformedFileAgainstSchema() throws Exception {
GenerateConnectorInspectionsMojo mojo = new GenerateConnectorInspectionsMojo();
String unformedConnectorFile = "my-unformed-connector.json";
assertThatExceptionOfType(MojoExecutionException.class)
.isThrownBy(() -> {
mojo.validateWithSchema(getFile("/" + unformedConnectorFile));
})
.withCauseInstanceOf(JsonParseException.class)
.withStackTraceContaining("line: 9, column: 12");
}
@Test
public void testIntegerFieldDoc() throws JsonParseException, IOException {
JsonParser parser = new JsonFactory().createParser(
"{ \"blix\" : 1234 }");
PushDownJsonHandler handler = new PushDownJsonHandler(parser);
TestDocumentHandler docHandler = new TestDocumentHandler();
handler.parseDocument(docHandler);
docHandler.child.assertNesting();
docHandler.child.assertField("blix");
assertEquals(new BigInteger("1234"), docHandler.child.bigIntegerValue);
}
@Test
public final void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect() throws JsonParseException, IOException {
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
final ObjectMapper mapper = new ObjectMapper();
final JsonNode actualObj = mapper.readTree(jsonString);
// When
final JsonNode jsonNode1 = actualObj.get("k1");
assertThat(jsonNode1.textValue(), equalTo("v1"));
}
@Test
public void testRecordDefinition()
throws AnalysisEngineProcessException, ResourceInitializationException, JsonParseException,
JsonMappingException, IOException {
processJCas(
TemplateRecordConfigurationCreatingConsumer.PARAM_OUTPUT_DIRECTORY,
tempDirectory.toString());
checkDefinitions();
}
public static Map string2Map(String str)
throws JsonParseException, IOException{
Map<String, Object> resMap;
ObjectMapper mapper = new ObjectMapper();
resMap = mapper.readValue(str, Map.class);
return resMap;
}
@Test
public void testReportGeneration() throws JsonParseException, JsonMappingException, IOException {
File file = new File(System.getProperty("user.home") + "/app-reporting-config.json");
if (file.exists()) {
ReportRequestSpec spec = mapper.readValue(file, ReportRequestSpec.class);
reporter.createReport(spec.getOutput(), spec.getInput());
Assertions.assertThat(new File(spec.getOutput()).exists()).isTrue();
}
}
public static String packServiceInfo(String current_json, Map<String, String> service_info) throws JsonParseException, JsonMappingException, IOException {
JsonNode new_top = BeanValidation.new_mapper.readTree(current_json);
String appType = service_info.get("appType");
if (appType != null) {
((ObjectNode)new_top).put("appType", appType);
}
return BeanValidation.new_mapper.writeValueAsString(new_top);
}
public T deserialize(byte[] value) throws JsonParseException, JsonMappingException, IOException {
if (null == value) {
return null;
}
return JsonUtil.readValue(value, type);
}
@Override
public Sha256Hash deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
Sha256Hash hash = Sha256Hash.fromString(node.asText());
if (hash == null) {
throw new JsonParseException("Failed to convert string '" + node.asText() + "' into a Sha256 hash",
JsonLocation.NA);
}
return hash;
}
private static Map<String, Object> deserializeObject(JsonParser jp) throws IOException {
ImmutableMapWithNullValues.Builder<String, Object> builder =
ImmutableMapWithNullValues.Builder.insertionOrder();
String fieldName;
while ((fieldName = jp.nextFieldName()) != null) {
builder.put(STRING_INTERNER.intern(fieldName), deserializeRecursive(jp, jp.nextToken()));
}
if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
throw new JsonParseException(jp, "Missing expected END_OBJECT");
}
return builder.build();
}
public PostmanEnvironment readEnvironmentFileClasspath(String fileOnClasspath) throws JsonParseException, JsonMappingException, IOException {
String fileName = fileOnClasspath.substring(fileOnClasspath.indexOf(":")+1);
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
PostmanEnvironment env = om.readValue(stream, PostmanEnvironment.class);
stream.close();
return env;
}
public <T> List<T> awaitMany(int count, Class<T> class1) throws JsonParseException, JsonProcessingException, IOException, InterruptedException {
List<T> result = new ArrayList<>();
for (int i = 0; i < count; i++) {
result.add(await(class1));
}
assertEquals(count, result.size());
return result;
}
@Test
public void throwExceptionOnInvalidUtf8Content() throws Exception {
exception.expectMessage("Invalid UTF-8");
exception.expect(JsonParseException.class);
try (InputStream in = new ByteArrayInputStream("{\"name\":\"foo\",\"author\":\"bé\"}".getBytes(ISO_8859_1))) {
try (JsonParser jsonParser = jsonFactory.createParser(in)) {
NpmPublishParser underTest = new NpmPublishParser(jsonParser, storageFacet, HASH_ALGORITHMS);
underTest.parse(NO_USER);
fail(); // exception should be thrown on parse
}
}
}
public static boolean readBoolean(JsonParser parser)
throws IOException, JsonReadException
{
try {
boolean b = parser.getBooleanValue();
parser.nextToken();
return b;
}
catch (JsonParseException ex) {
throw JsonReadException.fromJackson(ex);
}
}
private void setLocationInformation(
BulkUploadProcessTask task,
LocationClient locationClient,
Map<String, Location> locationCache,
ActorRef locationActor,
List<String> locationCodes)
throws IOException, JsonParseException, JsonMappingException {
ObjectMapper mapper = new ObjectMapper();
if (ProjectUtil.BulkProcessStatus.COMPLETED.getValue() == task.getStatus()) {
List<String> locationNames = new ArrayList<>();
for (String locationCode : locationCodes) {
if (locationCache.containsKey(locationCode)) {
locationNames.add(locationCache.get(locationCode).getName());
} else {
Location location = locationClient.getLocationByCode(locationActor, locationCode);
locationNames.add(location.getName());
}
}
Map<String, Object> row = mapper.readValue(task.getSuccessResult(), Map.class);
if (locationNames.size() == 1) {
row.put(JsonKey.LOCATION_NAME, locationNames.get(0));
row.put(JsonKey.LOCATION_CODE, locationCodes.get(0));
} else {
row.put(JsonKey.LOCATION_NAME, locationNames);
row.put(JsonKey.LOCATION_CODE, locationCodes);
}
task.setSuccessResult(mapper.writeValueAsString(row));
}
}