下面列出了怎么用com.fasterxml.jackson.databind.node.JsonNodeType的API类实例代码及写法,或者点击链接到github查看源代码。
private static boolean validateChainData(JsonNode data) throws Exception {
ECPublicKey lastKey = null;
boolean validChain = false;
for (JsonNode node : data) {
JWSObject jwt = JWSObject.parse(node.asText());
if (!validChain) {
validChain = verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
}
if (lastKey != null) {
verifyJwt(jwt, lastKey);
}
JsonNode payloadNode = Server.JSON_MAPPER.readTree(jwt.getPayload().toString());
JsonNode ipkNode = payloadNode.get("identityPublicKey");
Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
lastKey = EncryptionUtils.generateKey(ipkNode.asText());
}
return validChain;
}
@Test
public void testGetTasks() throws Exception {
Response response = target("/tasks").request().get();
assertResponseStatus(response, Response.Status.OK);
assertHeader(response.getHeaders(), HttpHeaders.CONTENT_TYPE, JsonApiMediaType.APPLICATION_JSON_API);
JsonNode data = mapper.readTree((InputStream) response.getEntity()).get("data");
assertThat(data.getNodeType(), is(JsonNodeType.ARRAY));
List<Task> tasks = new ArrayList<>();
for (JsonNode node : data) {
tasks.add(getTaskFromJson(node));
}
assertThat(tasks, hasSize(1));
final Task task = tasks.get(0);
assertThat(task.getId(), is(1L));
assertThat(task.getName(), is("First task"));
assertThat(task.getProject(), is(nullValue()));
}
@Test
public void verifiedWithJacksonParser() throws Exception {
ODataServerError error =
new ODataServerError().setCode("Code").setMessage("Message").setTarget("Target")
.setDetails(Collections.singletonList(
new ODataErrorDetail().setCode("detailCode").setMessage("detailMessage").setTarget("detailTarget")));
InputStream stream = ser.error(error).getContent();
JsonNode tree = new ObjectMapper().readTree(stream);
assertNotNull(tree);
tree = tree.get("error");
assertNotNull(tree);
assertEquals("Code", tree.get("code").textValue());
assertEquals("Message", tree.get("message").textValue());
assertEquals("Target", tree.get("target").textValue());
tree = tree.get("details");
assertNotNull(tree);
assertEquals(JsonNodeType.ARRAY, tree.getNodeType());
tree = tree.get(0);
assertNotNull(tree);
assertEquals("detailCode", tree.get("code").textValue());
assertEquals("detailMessage", tree.get("message").textValue());
assertEquals("detailTarget", tree.get("target").textValue());
}
public static Optional<ArrayNode> getArrayNode(
final ObjectNode json, final String fieldKey, final boolean strict) {
final JsonNode obj = json.get(fieldKey);
if (obj == null || obj.isNull()) {
return Optional.empty();
}
if (!obj.isArray()) {
if (strict) {
validateType(obj, JsonNodeType.ARRAY);
} else {
return Optional.empty();
}
}
return Optional.of((ArrayNode) obj);
}
public List<Server> getServersList(ArrayNode obj, String location, ParseResult result, String path) {
List<Server> servers = new ArrayList<>();
if (obj == null) {
return null;
}
for (JsonNode item : obj) {
if (item.getNodeType().equals(JsonNodeType.OBJECT)) {
Server server = getServer((ObjectNode) item, location, result, path);
if (server != null) {
servers.add(server);
}else{
Server defaultServer = new Server();
defaultServer.setUrl("/");
servers.add(defaultServer);
}
}
}
return servers;
}
private static JsonNode checkException(JsonNode jsonException, Class<?> expectedType, String expectedMessage){
assertThat(jsonException.get("type").textValue()).isEqualTo(expectedType.getName());
assertThat(jsonException.get("message").textValue()).isEqualTo(expectedMessage);
JsonNode jsonStackTrace = jsonException.get("stacktrace");
assertThat(jsonStackTrace.getNodeType()).isEqualTo(JsonNodeType.ARRAY);
assertThat(jsonStackTrace).isNotNull();
for (JsonNode stackTraceElement : jsonStackTrace) {
assertThat(stackTraceElement.get("filename")).isNotNull();
assertThat(stackTraceElement.get("classname")).isNotNull();
assertThat(stackTraceElement.get("function")).isNotNull();
assertThat(stackTraceElement.get("library_frame")).isNotNull();
assertThat(stackTraceElement.get("lineno")).isNotNull();
assertThat(stackTraceElement.get("module")).isNotNull();
}
return jsonException;
}
@Test
void testSpanStackFrameSerialization() {
Span span = new Span(MockTracer.create());
span.setStackTrace(Arrays.asList(StackFrame.of("foo.Bar", "baz"), StackFrame.of("foo.Bar$Baz", "qux")));
JsonNode spanJson = readJsonString(serializer.toJsonString(span));
JsonNode jsonStackTrace = spanJson.get("stacktrace");
assertThat(jsonStackTrace.getNodeType()).isEqualTo(JsonNodeType.ARRAY);
assertThat(jsonStackTrace).isNotNull();
assertThat(jsonStackTrace).hasSize(2);
assertThat(jsonStackTrace.get(0).get("filename").textValue()).isEqualTo("Bar.java");
assertThat(jsonStackTrace.get(0).get("function").textValue()).isEqualTo("baz");
assertThat(jsonStackTrace.get(0).get("library_frame").booleanValue()).isTrue();
assertThat(jsonStackTrace.get(0).get("lineno").intValue()).isEqualTo(-1);
assertThat(jsonStackTrace.get(0).get("module")).isNull();
assertThat(jsonStackTrace.get(1).get("filename").textValue()).isEqualTo("Bar.java");
assertThat(jsonStackTrace.get(1).get("function").textValue()).isEqualTo("qux");
assertThat(jsonStackTrace.get(1).get("library_frame").booleanValue()).isTrue();
assertThat(jsonStackTrace.get(1).get("lineno").intValue()).isEqualTo(-1);
assertThat(jsonStackTrace.get(1).get("module")).isNull();
}
/** Get the value of an example. This can be direct value field or those of followed $ref */
private String getExampleValue(JsonNode example) {
if (example.has("value")) {
if (example.path("value").getNodeType() == JsonNodeType.ARRAY ||
example.path("value").getNodeType() == JsonNodeType.OBJECT ) {
return example.path("value").toString();
}
return example.path("value").asText();
}
if (example.has("$ref")) {
// $ref: '#/components/examples/param_laurent'
String ref = example.path("$ref").asText();
JsonNode component = spec.at(ref.substring(1));
return getExampleValue(component);
}
return null;
}
public Integer getInteger(String key, ObjectNode node, boolean required, String location, ParseResult result) {
Integer value = null;
JsonNode v = node.get(key);
if (node == null || v == null) {
if (required) {
result.missing(location, key);
result.invalid();
}
}
else if(v.getNodeType().equals(JsonNodeType.NUMBER)) {
if (v.isInt()) {
value = v.intValue();
}
}
else if(!v.isValueNode()) {
result.invalidType(location, key, "integer", node);
}
return value;
}
@Test
public void remove() {
String input = "{\n" +
" \"name\":\"John\",\n" +
" \"age\":30,\n" +
" \"cars\": {\n" +
" \"car1\":\"Ford\",\n" +
" \"car2\":\"BMW\",\n" +
" \"car3\":\"Fiat\"\n" +
" }\n" +
" }";
JsonNode parse = jsonUtils.parse(input);
jsonUtils.remove(parse, "age");
Assertions.assertThat(parse.at("/age").getNodeType()).isEqualTo(JsonNodeType.MISSING);
jsonUtils.remove(parse, "cars.car3");
Assertions.assertThat(parse.at("/cars/cars3").getNodeType()).isEqualTo(JsonNodeType.MISSING);
}
protected JsonNodeType nodeTypeFor(Object value) {
JsonNodeType type;
if (value == null) {
type = JsonNodeType.NULL;
} else if (value instanceof Boolean) {
type = JsonNodeType.BOOLEAN;
} else if (value instanceof Number) {
type = JsonNodeType.NUMBER;
} else if (value instanceof String) {
type = JsonNodeType.STRING;
} else if (value instanceof ArrayNode || value instanceof List) {
type = JsonNodeType.ARRAY;
} else if (value instanceof byte[]) {
type = JsonNodeType.BINARY;
} else if (value instanceof ObjectNode || value instanceof Map) {
type = JsonNodeType.OBJECT;
} else {
type = JsonNodeType.POJO;
}
return type;
}
private Set<String> decodeTags(JsonNode tree, String name) {
final JsonNode n = tree.get(name);
if (n == null) {
return EMPTY_TAGS;
}
if (n.getNodeType() != JsonNodeType.ARRAY) {
return EMPTY_TAGS;
}
final List<String> tags = Lists.newArrayList();
final Iterator<JsonNode> iter = n.elements();
while (iter.hasNext()) {
tags.add(iter.next().asText());
}
return Sets.newHashSet(tags);
}
@Before
public void setUp() throws Exception {
expectedFlattenMap = new HashMap<>();
expectedFlattenMap.put("ts",
JsonParsingService.JsonPathData.builder()
.value("2016-03-03T18:15:00Z")
.types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.STRING})).build());
expectedFlattenMap.put("value",
JsonParsingService.JsonPathData.builder()
.value(31.0)
.types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.NUMBER})).build());
expectedFlattenMap.put("command.type",
JsonParsingService.JsonPathData.builder()
.value("ButtonPressed")
.types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.OBJECT,JsonNodeType.STRING})).build());
expectedFlattenMap.put("data.channels.0.name",
JsonParsingService.JsonPathData.builder()
.value("channel_0")
.types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.OBJECT,JsonNodeType.ARRAY,JsonNodeType.OBJECT,JsonNodeType.STRING})).build());
expectedFlattenMap.put("time",
JsonParsingService.JsonPathData.builder()
.value(123L)
.types(Arrays.asList(new JsonNodeType[] {JsonNodeType.OBJECT,JsonNodeType.NUMBER})).build());
}
static ObjectNode readTree(final ByteBuf in) {
checkNotNull(in, "in");
final JsonNode node;
try (final InputStream istream = new ByteBufInputStream(in)) {
node = objectMapper.readTree(istream);
} catch (final IOException error) {
throw new CorruptedFrameException(error);
}
if (node.isObject()) {
return (ObjectNode)node;
}
final String cause = lenientFormat("Expected %s, not %s", JsonNodeType.OBJECT, node.getNodeType());
throw new CorruptedFrameException(cause);
}
private static Map<String, RepositoryInfo> listRepositories(AggregatedHttpResponse res) {
switch (res.status().code()) {
case 200:
return Streams.stream(toJson(res, JsonNodeType.ARRAY))
.map(node -> {
final String name = getField(node, "name").asText();
final Revision headRevision =
new Revision(getField(node, "headRevision").asInt());
return new RepositoryInfo(name, headRevision);
})
.collect(toImmutableMap(RepositoryInfo::name, Function.identity()));
case 204:
return ImmutableMap.of();
}
return handleErrorResponse(res);
}
/**
* Parses the content of the specified {@link AggregatedHttpResponse} into a {@link JsonNode}.
*/
private static JsonNode toJson(AggregatedHttpResponse res, @Nullable JsonNodeType expectedNodeType) {
final String content = toString(res);
final JsonNode node;
try {
node = Jackson.readTree(content);
} catch (JsonParseException e) {
throw new CentralDogmaException("failed to parse the response JSON", e);
}
if (expectedNodeType != null && node.getNodeType() != expectedNodeType) {
throw new CentralDogmaException(
"invalid server response; expected: " + expectedNodeType +
", actual: " + node.getNodeType() + ", content: " + content);
}
return node;
}
private static <T> T handleErrorResponse(AggregatedHttpResponse res) {
final HttpStatus status = res.status();
if (status.codeClass() != HttpStatusClass.SUCCESS) {
final JsonNode node = toJson(res, JsonNodeType.OBJECT);
final JsonNode exceptionNode = node.get("exception");
final JsonNode messageNode = node.get("message");
if (exceptionNode != null) {
final String typeName = exceptionNode.textValue();
if (typeName != null) {
final Function<String, CentralDogmaException> exceptionFactory =
EXCEPTION_FACTORIES.get(typeName);
if (exceptionFactory != null) {
throw exceptionFactory.apply(messageNode.textValue());
}
}
}
}
throw new CentralDogmaException("unexpected response: " + res.headers() + ", " + res.contentUtf8());
}
public static OptionalInt getInt(final ObjectNode node, final String key) {
return getValue(node, key)
.filter(jsonNode -> validateType(jsonNode, JsonNodeType.NUMBER))
.filter(JsonUtil::validateInt)
.map(JsonNode::asInt)
.map(OptionalInt::of)
.orElse(OptionalInt.empty());
}
public List<Example> getExampleList(ArrayNode obj, String location, ParseResult result) {
List<Example> examples = new ArrayList<>();
if (obj == null) {
return examples;
}
for (JsonNode item : obj) {
if (item.getNodeType().equals(JsonNodeType.OBJECT)) {
Example example = getExample((ObjectNode) item, location, result);
if (example != null) {
examples.add(example);
}
}
}
return examples;
}
public Map<String, RequestBody> getRequestBodies(ObjectNode obj, String location, ParseResult result, boolean underComponents) {
if (obj == null) {
return null;
}
Map<String, RequestBody> bodies = new LinkedHashMap<>();
Set<String> bodyKeys = getKeys(obj);
for(String bodyName : bodyKeys) {
if(underComponents) {
if (!Pattern.matches("^[a-zA-Z0-9\\.\\-_]+$",
bodyName)) {
result.warning(location, "RequestBody name " + bodyName + " doesn't adhere to regular expression ^[a-zA-Z0-9\\.\\-_]+$");
}
}
JsonNode bodyValue = obj.get(bodyName);
if (!bodyValue.getNodeType().equals(JsonNodeType.OBJECT)) {
result.invalidType(location, bodyName, "object", bodyValue);
} else {
ObjectNode bodyObj = (ObjectNode) bodyValue;
RequestBody body = getRequestBody(bodyObj, String.format("%s.%s", location, bodyName), result);
if(body != null) {
bodies.put(bodyName, body);
}
}
}
return bodies;
}
public Callback getCallback(ObjectNode node,String location, ParseResult result) {
if (node == null) {
return null;
}
Callback callback = new Callback();
Set<String> keys = getKeys(node);
for(String name : keys) {
JsonNode value = node.get(name);
if (node!= null){
JsonNode ref = node.get("$ref");
if (ref != null) {
if (ref.getNodeType().equals(JsonNodeType.STRING)) {
String mungedRef = mungedRef(ref.textValue());
if (mungedRef != null) {
callback.set$ref(mungedRef);
}else{
callback.set$ref(ref.textValue());
}
return callback;
} else {
result.invalidType(location, "$ref", "string", node);
return null;
}
}
callback.addPathItem(name,getPathItem((ObjectNode) value,location,result));
Map <String,Object> extensions = getExtensions(node);
if(extensions != null && extensions.size() > 0) {
callback.setExtensions(extensions);
}
}
}
return callback;
}
public static void encryptPlayerConnection(GeyserConnector connector, GeyserSession session, LoginPacket loginPacket) {
JsonNode certData;
try {
certData = JSON_MAPPER.readTree(loginPacket.getChainData().toByteArray());
} catch (IOException ex) {
throw new RuntimeException("Certificate JSON can not be read.");
}
JsonNode certChainData = certData.get("chain");
if (certChainData.getNodeType() != JsonNodeType.ARRAY) {
throw new RuntimeException("Certificate data is not valid");
}
encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);
}
@Test
@Parameters
public void testCustomSchemaDefinition_asStrings(SchemaVersion schemaVersion, EnumModule instance,
String value1, String value2, String value3) {
this.initConfigBuilder(schemaVersion);
instance.applyToConfigBuilder(this.builder);
ArgumentCaptor<CustomDefinitionProviderV2> captor = ArgumentCaptor.forClass(CustomDefinitionProviderV2.class);
Mockito.verify(this.typeConfigPart).withCustomDefinitionProvider(captor.capture());
ResolvedType testEnumType = this.getContext().getTypeContext().resolve(TestEnum.class);
CustomDefinition schemaDefinition = captor.getValue().provideCustomSchemaDefinition(testEnumType, this.getContext());
Assert.assertFalse(schemaDefinition.isMeantToBeInline());
ObjectNode node = schemaDefinition.getValue();
Assert.assertEquals(2, node.size());
JsonNode typeNode = node.get(SchemaKeyword.TAG_TYPE.forVersion(schemaVersion));
Assert.assertEquals(JsonNodeType.STRING, typeNode.getNodeType());
Assert.assertEquals(SchemaKeyword.TAG_TYPE_STRING.forVersion(schemaVersion), typeNode.textValue());
JsonNode enumNode = node.get(SchemaKeyword.TAG_ENUM.forVersion(schemaVersion));
Assert.assertEquals(JsonNodeType.ARRAY, enumNode.getNodeType());
Assert.assertEquals(3, ((ArrayNode) enumNode).size());
Assert.assertEquals(JsonNodeType.STRING, enumNode.get(0).getNodeType());
Assert.assertEquals(value1, enumNode.get(0).textValue());
Assert.assertEquals(JsonNodeType.STRING, enumNode.get(1).getNodeType());
Assert.assertEquals(value2, enumNode.get(1).textValue());
Assert.assertEquals(JsonNodeType.STRING, enumNode.get(2).getNodeType());
Assert.assertEquals(value3, enumNode.get(2).textValue());
}
private synchronized static void readJsonStoreCache(JsonNode m)
{
if (m == null || !m.getNodeType().equals(JsonNodeType.OBJECT))
{
LOGGER.debug("Invalid cache file format.");
return;
}
try
{
for (Iterator<Map.Entry<String, JsonNode>> itr = m.fields(); itr.hasNext(); )
{
SFPair<OcspResponseCacheKey, SFPair<Long, String>> ky =
decodeCacheFromJSON(itr.next());
if (ky != null && ky.right != null && ky.right.right != null)
{
// valid range. cache the result in memory
OCSP_RESPONSE_CACHE.put(ky.left, ky.right);
WAS_CACHE_UPDATED.set(true);
}
else if (ky != null && OCSP_RESPONSE_CACHE.containsKey(ky.left))
{
// delete it from the cache if no OCSP response is back.
OCSP_RESPONSE_CACHE.remove(ky.left);
WAS_CACHE_UPDATED.set(true);
}
}
}
catch (IOException ex)
{
LOGGER.debug("Failed to decode the cache file");
}
}
/**
* Convert an opaque JSON node to Decimal using the most correct
* conversion method.
*/
public static Decimal nodeToDecimal(JsonNode node) {
JsonNodeType type = node.getNodeType();
if (type == JsonNodeType.NUMBER) {
return numericToDecimal((NumericNode)node);
} else {
try {
return new Decimal(node.asText());
} catch (ArithmeticException | NumberFormatException e) {
// Fall through..
}
}
return null;
}
public Object getAnyExample(String nodeKey,ObjectNode node, String location, ParseResult result ){
JsonNode example = node.get(nodeKey);
if (example != null) {
if (example.getNodeType().equals(JsonNodeType.STRING)) {
return getString(nodeKey, node, false, location, result);
} if (example.getNodeType().equals(JsonNodeType.NUMBER)) {
Integer integerExample = getInteger(nodeKey, node, false, location, result);
if (integerExample != null) {
return integerExample;
}else {
BigDecimal bigDecimalExample = getBigDecimal(nodeKey, node, false, location, result);
if (bigDecimalExample != null) {
return bigDecimalExample;
}
}
} else if (example.getNodeType().equals(JsonNodeType.OBJECT)) {
ObjectNode objectValue = getObject(nodeKey, node, false, location, result);
if (objectValue != null) {
return objectValue;
}
} else if (example.getNodeType().equals(JsonNodeType.ARRAY)) {
ArrayNode arrayValue = getArray(nodeKey, node, false, location, result);
if (arrayValue != null) {
return arrayValue;
}
} else if (example.getNodeType().equals(JsonNodeType.BOOLEAN)){
Boolean bool = getBoolean(nodeKey,node,false,location,result);
if (bool != null){
return bool;
}
}
}
return null;
}
@Test
public void put() {
String input = "{ \"name\":\"John\", \"age\":30}";
JsonNode parse = jsonUtils.parse(input);
jsonUtils.put(parse, "car.type", JsonNodeFactory.instance.textNode("test"));
Assertions.assertThat(parse.at("/car").getNodeType()).isEqualTo(JsonNodeType.OBJECT);
Assertions.assertThat(parse.at("/car/type").asText()).isEqualTo("test");
}
@Test
public void putMultiLevel() {
String input = "{ \"name\":\"John\", \"age\":30}";
JsonNode parse = jsonUtils.parse(input);
jsonUtils.put(parse, "car.model.name", JsonNodeFactory.instance.textNode("multipla"));
Assertions.assertThat(parse.at("/car").getNodeType()).isEqualTo(JsonNodeType.OBJECT);
Assertions.assertThat(parse.at("/car/model").getNodeType()).isEqualTo(JsonNodeType.OBJECT);
Assertions.assertThat(parse.at("/car/model/name").asText()).isEqualTo("multipla");
}
public List<Parameter> getParameterList(ArrayNode obj, String location, ParseResult result) {
List<Parameter> parameters = new ArrayList<>();
if (obj == null) {
return parameters;
}
for (JsonNode item : obj) {
if (item.getNodeType().equals(JsonNodeType.OBJECT)) {
Parameter parameter = getParameter((ObjectNode) item, location, result);
if (parameter != null) {
parameters.add(parameter);
}
}
}
Set<String> filter = new HashSet<>();
parameters.stream().map(this::getParameterDefinition).forEach(param -> {
String ref = param.get$ref();
if(!filter.add(param.getName()+"#"+param.getIn())) {
if(ref != null) {
if (ref.startsWith(REFERENCE_SEPARATOR)) {// validate if it's inline param also
result.warning(location, "There are duplicate parameter values");
}
}else{
result.warning(location, "There are duplicate parameter values");
}
}
});
return parameters;
}
public List<SecurityRequirement> getSecurityRequirementsList(ArrayNode nodes, String location, ParseResult result) {
if (nodes == null)
return null;
List<SecurityRequirement> securityRequirements = new ArrayList<>();
for (JsonNode node : nodes) {
if (node.getNodeType().equals(JsonNodeType.OBJECT)) {
SecurityRequirement securityRequirement = new SecurityRequirement();
Set<String> keys = getKeys((ObjectNode) node);
if (keys.size() == 0){
securityRequirements.add(securityRequirement);
}else {
for (String key : keys) {
if (key != null) {
JsonNode value = node.get(key);
if (key != null && JsonNodeType.ARRAY.equals(value.getNodeType())) {
ArrayNode arrayNode = (ArrayNode) value;
List<String> scopes = Stream
.generate(arrayNode.elements()::next)
.map((n) -> n.asText())
.limit(arrayNode.size())
.collect(Collectors.toList());
securityRequirement.addList(key, scopes);
}
}
}
if (securityRequirement.size() > 0) {
securityRequirements.add(securityRequirement);
}
}
}
}
return securityRequirements;
}