下面列出了怎么用com.fasterxml.jackson.core.TreeNode的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testBodyJsonClaimsInformationPoint() throws Exception {
Map<String, List<String>> headers = new HashMap<>();
headers.put("Content-Type", Arrays.asList("application/json"));
ObjectMapper mapper = JsonSerialization.mapper;
JsonParser parser = mapper.getFactory().createParser("{\"a\": {\"b\": {\"c\": \"c-value\"}}, \"d\": [\"d-value1\", \"d-value2\"], \"e\": {\"number\": 123}}");
TreeNode treeNode = mapper.readTree(parser);
HttpFacade httpFacade = createHttpFacade(headers, new ByteArrayInputStream(treeNode.toString().getBytes()));
Map<String, List<String>> claims = getClaimInformationProviderForPath("/claims-provider", "claims").resolve(httpFacade);
assertEquals("c-value", claims.get("claim-from-json-body-object").get(0));
assertEquals("d-value2", claims.get("claim-from-json-body-array").get(0));
assertEquals("123", claims.get("claim-from-json-body-number").get(0));
}
/**
* Convert raw data to {@code Node}
* @param parser - JSON reader
* @return path node
* @throws IOException
*/
private Node toNode(JsonParser parser) throws IOException {
ObjectCodec codec = parser.getCodec();
TreeNode tree = parser.readValueAsTree();
String tag = codec.treeToValue(tree.path(FieldName.TAG), String.class);
Integer index = codec.treeToValue(tree.path(FieldName.INDEX), Integer.class);
String innerText = codec.treeToValue(tree.path(FieldName.INNER_TEXT), String.class);
String id = codec.treeToValue(tree.path(FieldName.ID), String.class);
//noinspection unchecked
Set<String> classes = codec.treeToValue(tree.path(FieldName.CLASSES), Set.class);
//noinspection unchecked
Map<String, String> attributes = codec.treeToValue(tree.path(FieldName.OTHER), Map.class);
return new NodeBuilder()
//TODO: fix attribute setting, because they override 'id' and 'classes' property
.setAttributes(attributes)
.setTag(tag)
.setIndex(index)
.setId(id)
.addContent(innerText)
.setClasses(classes)
.build();
}
@Override
public InfoDTO deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
InfoDTO infoDTO = new InfoDTO();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
TextNode appNameNode = (TextNode) treeNode.get("appName");
infoDTO.setAppName(appNameNode.asText());
TextNode versionNode = (TextNode) treeNode.get("version");
infoDTO.setVersion(versionNode.asText());
TextNode dateNode = (TextNode) treeNode.get("date");
try {
infoDTO.setDate(sdf.parse(dateNode.asText()));
} catch (ParseException e) {
e.printStackTrace();
}
return infoDTO;
}
private Map<Object, Class<?>> fetchParameterMap(TreeNode paramsNode) throws IOException {
try {
final Map<Object, Class<?>> parameterMap = new HashMap<>();
final Iterator<String> paramsFieldNamesIterator = paramsNode.fieldNames();
String parameterValueAsString;
Class<?> parameterType;
while (paramsFieldNamesIterator.hasNext()) {
parameterValueAsString = trimJSONQuotes(paramsFieldNamesIterator.next());
parameterType = Class.forName(trimJSONQuotes(paramsNode.get(parameterValueAsString).toString()));
parameterMap.put(cast(parameterValueAsString, parameterType), parameterType);
}
return parameterMap;
} catch (Exception e) {
throw new IOException("Error while fetching parameters " + paramsNode, e);
}
}
@Override
public Sort deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
if (treeNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) treeNode;
List<Sort.Order> orders = new ArrayList<>();
for (JsonNode jsonNode : arrayNode) {
Sort.Order order = new Sort.Order(
Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
jsonNode.get("property").textValue());
orders.add(order);
}
return Sort.by(orders);
}
return null;
}
public void testSimpleMixed() throws Exception
{
final String INPUT = "{\"a\":[1,2,{\"b\":true},3],\"c\":3}";
TreeNode node = TREE_CODEC.readTree(_factory.createParser(READ_CONTEXT, INPUT));
assertTrue(node instanceof JrsObject);
assertEquals(2, node.size());
TreeNode list = node.get("a");
assertTrue(list instanceof JrsArray);
// actually, verify with write...
final StringWriter writer = new StringWriter();
final JsonGenerator g = _factory.createGenerator(WRITE_CONTEXT, writer);
TREE_CODEC.writeTree(g, node);
g.close();
assertEquals(INPUT, writer.toString());
}
@Override
public List<LSServerFilter> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
List<LSServerFilter> filters = new ArrayList<>();
for (JsonNode filterNode : node) {
if (filterNode.get("filter") == null) {
throw new IllegalArgumentException("Each filter element must have a field called 'filter' declaring it's type");
}
switch (filterNode.get("filter").asText()) {
case "grok" :
filters.add(oc.treeToValue((TreeNode)filterNode, LSServerFilterGrok.class));
break;
case "keyvalue" :
filters.add(oc.treeToValue((TreeNode)filterNode, LSServerFilterKeyValue.class));
break;
case "json" :
filters.add(oc.treeToValue((TreeNode)filterNode, LSServerFilterJson.class));
break;
}
}
return filters;
}
@SuppressWarnings("unchecked")
public ComponentInstance readAsTree(final TreeNode p) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// read the parameter values
Map<String, String> parameterValues = mapper.treeToValue(p.get("params"), HashMap.class);
// read the component
String componentName = p.get("component").toString().replaceAll("\"", "");
Component component = this.possibleComponents.stream().filter(c -> c.getName().equals(componentName)).findFirst()
.orElseThrow(NoSuchElementException::new);
Map<String, ComponentInstance> satisfactionOfRequiredInterfaces = new HashMap<>();
// recursively resolve the requiredInterfaces
TreeNode n = p.get("requiredInterfaces");
Iterator<String> fields = n.fieldNames();
while (fields.hasNext()) {
String key = fields.next();
satisfactionOfRequiredInterfaces.put(key, this.readAsTree(n.get(key)));
}
return new ComponentInstance(component, parameterValues, satisfactionOfRequiredInterfaces);
}
@Override
public PrivateTransaction deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
final TreeNode node = p.readValueAsTree();
// Select the concrete class based on the existence of a property
if (node.get("privateFor") != null && node.get("privateFor").isArray()) {
return p.getCodec().treeToValue(node, PrivateTransactionLegacy.class);
} else if ((node.get("privateFor") != null && node.get("privateFor").isValueNode())
|| (node.get("privacyGroupId") != null
&& node.get("privacyGroupId").isValueNode())) {
return p.getCodec().treeToValue(node, PrivateTransactionWithPrivacyGroup.class);
}
return null;
}
private List<KnoxShellTableCall> parseCallHistoryListJSONNode(TreeNode callHistoryNode) throws IOException {
final List<KnoxShellTableCall> callHistoryList = new LinkedList<>();
TreeNode callNode;
Map<Object, Class<?>> params;
String invokerClass, method;
Boolean builderMethod;
for (int i = 0; i < callHistoryNode.size(); i++) {
callNode = callHistoryNode.get(i);
invokerClass = trimJSONQuotes(callNode.get("invokerClass").toString());
method = trimJSONQuotes(callNode.get("method").toString());
builderMethod = Boolean.valueOf(trimJSONQuotes(callNode.get("builderMethod").toString()));
params = fetchParameterMap(callNode.get("params"));
callHistoryList.add(new KnoxShellTableCall(invokerClass, method, builderMethod, params));
}
return callHistoryList;
}
/** This is used to populate the error location or the node which causes the error.. */
private void populateSiteErrorMessage(
TreeNode node, StringBuilder errorMessage, JsonNode jsonNode) {
String path = jsonNode.get("instance").get("pointer").asText();
String[] splitPaths = path.split("/");
// this means some node inside the top level has a problem..
if (splitPaths.length > 1) {
try {
// this represents the location of error..
int location = Integer.parseInt(splitPaths[2]);
TreeNode nodeDetails = node.get("site").get(location);
errorMessage.append(nodeDetails);
} catch (Exception e) {
errorMessage.append(path);
}
} else {
errorMessage.append("top level error");
}
}
private KnoxShellTable parseJsonWithData(final TreeNode jsonContent) {
if (jsonContent.get("title").size() != 0) {
table.title(trimJSONQuotes(jsonContent.get("title").toString()));
}
final TreeNode headers = jsonContent.get("headers");
for (int i = 0; i < headers.size(); i++) {
table.header(trimJSONQuotes(headers.get(i).toString()));
}
final TreeNode rows = jsonContent.get("rows");
for (int i = 0; i < rows.size(); i++) {
TreeNode row = rows.get(i);
table.row();
for (int j = 0; j < row.size(); j++) {
table.value(trimJSONQuotes(row.get(j).toString()));
}
}
return table;
}
/** Converts the provided {@link Struct} into {@link PipelineOptions}. */
public static PipelineOptions fromProto(Struct protoOptions) {
try {
Map<String, TreeNode> mapWithoutUrns = new HashMap<>();
TreeNode rootOptions = MAPPER.readTree(JsonFormat.printer().print(protoOptions));
Iterator<String> optionsKeys = rootOptions.fieldNames();
while (optionsKeys.hasNext()) {
String optionKey = optionsKeys.next();
TreeNode optionValue = rootOptions.get(optionKey);
mapWithoutUrns.put(
CaseFormat.LOWER_UNDERSCORE.to(
CaseFormat.LOWER_CAMEL,
optionKey.substring("beam:option:".length(), optionKey.length() - ":v1".length())),
optionValue);
}
return MAPPER.readValue(
MAPPER.writeValueAsString(ImmutableMap.of("options", mapWithoutUrns)),
PipelineOptions.class);
} catch (IOException e) {
throw new RuntimeException("Failed to read PipelineOptions from Protocol", e);
}
}
@Override
public List<Pair<AccountName, Long>> deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
List<Pair<AccountName, Long>> result = new ArrayList<>();
ObjectCodec codec = jsonParser.getCodec();
TreeNode rootNode = codec.readTree(jsonParser);
if (rootNode.isArray()) {
for (JsonNode node : (ArrayNode) rootNode) {
// result.put((node.get(0)).asText(), (node.get(0)).asInt());
}
return result;
}
throw new IllegalArgumentException("JSON Node is not an array.");
}
@Override
public List<Pair<String, Long>> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
List<Pair<String, Long>> result = new ArrayList<>();
ObjectCodec codec = jsonParser.getCodec();
TreeNode rootNode = codec.readTree(jsonParser);
if (rootNode.isArray()) {
for (JsonNode node : (ArrayNode) rootNode) {
// result.put((node.get(0)).asText(), (node.get(0)).asInt());
}
return result;
}
throw new IllegalArgumentException("JSON Node is not an array.");
}
@Override
public Map<String, Integer> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
HashMap<String, Integer> result = new HashMap<>();
ObjectCodec codec = jsonParser.getCodec();
TreeNode rootNode = codec.readTree(jsonParser);
if (rootNode.isArray()) {
for (JsonNode node : (ArrayNode) rootNode) {
result.put((node.get(0)).asText(), (node.get(0)).asInt());
}
return result;
}
throw new IllegalArgumentException("JSON Node is not an array.");
}
@Override
public Map<PublicKey, Integer> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
HashMap<PublicKey, Integer> result = new HashMap<>();
ObjectCodec codec = jsonParser.getCodec();
TreeNode rootNode = codec.readTree(jsonParser);
if (rootNode.isArray()) {
for (JsonNode node : (ArrayNode) rootNode) {
PublicKey publicKey = new PublicKey((node.get(0)).asText());
result.put(publicKey, (node.get(0)).asInt());
}
return result;
}
throw new IllegalArgumentException("JSON Node is not an array.");
}
@Override
public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
JsonLocation l = jp.getTokenLocation();
// logger.debug("Reading tree.");
TreeNode n = jp.readValueAsTree();
// logger.debug("Tree {}", n);
if (n instanceof JsonNode) {
return new JSONOptions( (JsonNode) n, l);
} else {
throw new IllegalArgumentException(String.format("Received something other than a JsonNode %s", n));
}
}
private KnoxShellTable parseJsonWithCallHistory(TreeNode jsonContent) throws IOException {
final List<KnoxShellTableCall> calls = parseCallHistoryListJSONNode(jsonContent.get("callHistoryList"));
long tempId = KnoxShellTable.getUniqueTableId();
KnoxShellTableCallHistory.getInstance().saveCalls(tempId, calls);
final KnoxShellTable tableFromJson = KnoxShellTableCallHistory.getInstance().replay(tempId, calls.size());
table.rows = tableFromJson.rows;
KnoxShellTableCallHistory.getInstance().removeCallsById(tempId);
KnoxShellTableCallHistory.getInstance().removeCallsById(tableFromJson.id);
return table;
}
@Override
public UnknownRequestContainer deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
TreeNode tree = p.getCodec().readTree(p);
return new UnknownRequestContainer(tree);
}
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
TreeNode tree = jp.getCodec().readTree(jp);
return tree.toString();
}
@SuppressWarnings("unchecked")
public static <T extends MessageOrBuilder> T writeAndReadBack(ObjectMapper mapper, T value) {
TreeNode tree = toTree(mapper, value);
try {
return (T) mapper.treeToValue(tree, value.getClass());
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public List<LSServerInput> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
List<LSServerInput> inputs = new ArrayList<>();
for (JsonNode inputNode : node) {
String source = null;
if (inputNode.get("source") != null) {
source = inputNode.get("source").asText();
} else {
source = (inputNode.get("s3_access_key") != null || inputNode.get("s3_secret_key") != null) ? "s3_file" : "file";
}
switch (source) {
case "file" :
inputs.add(oc.treeToValue((TreeNode)inputNode, LSServerInputFile.class));
break;
case "s3_file" :
inputs.add(oc.treeToValue((TreeNode)inputNode, LSServerInputS3File.class));
break;
}
}
return inputs;
}
@Override
public KnoxShellTable deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
final TreeNode jsonContent = parser.readValueAsTree();
if (jsonContent.get("callHistoryList") != null) {
return parseJsonWithCallHistory(jsonContent);
} else {
return parseJsonWithData(jsonContent);
}
}
protected PaginatedList<String> pagedQueryViewOfIds(String viewName, ComplexKey startKey, ComplexKey endKey, PaginationOffset pagination) {
int limit = pagination != null && pagination.getLimit() != null ? pagination.getLimit() : DEFAULT_LIMIT;
int page = pagination != null && pagination.getPage() != null ? pagination.getPage() : 1;
String startDocId = pagination != null ? pagination.getStartDocumentId() : null;
ViewQuery viewQuery = createQuery(viewName)
.startKey(startKey)
.reduce(false)
.limit(limit)
.includeDocs(false);
if (endKey != null) {
viewQuery = viewQuery.endKey(endKey);
}
PageRequest pr = new PageRequest.Builder().pageSize(limit).page(page).nextKey(new PageRequest.KeyIdPair(pagination.getStartKey() == null ? null : ((ComplexKey)pagination.getStartKey()).toJson(), startDocId)).build();
Page<String> ts = db.queryForPage(viewQuery, pr, String.class);
try {
return new PaginatedList<>(
ts.getPageSize(),
ts.getTotalSize(),
ts.getRows(),
ts.getTotalSize() > ts.getPageSize() && ts.getNextPageRequest() != null ? new PaginatedDocumentKeyIdPair(MAPPER.treeToValue((TreeNode) ts.getNextPageRequest().getStartKey(), List.class), ts.getNextPageRequest().getStartKeyDocId()) : null
);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
TreeNode tree = jp.getCodec().readTree(jp);
return tree.toString();
}
@Override
@SuppressWarnings("TypeParameterUnusedInFormals")
public <T extends TreeNode> T readTree(final JsonParser p) throws IOException {
final T ret = delegate.readTree(p);
captured = ret;
return ret;
}
private Duration deserializeObject(TreeNode tree, DeserializationContext c)
throws JsonMappingException {
if (tree == null) {
throw c.mappingException("expected object");
}
TreeNode node;
ValueNode valueNode;
final long duration;
final TimeUnit unit;
if ((node = tree.get("duration")) != null && node.isValueNode() &&
(valueNode = (ValueNode) node).isNumber()) {
duration = valueNode.asLong();
} else {
throw c.mappingException("duration is not a numeric field");
}
if ((node = tree.get("unit")) != null && node.isValueNode() &&
(valueNode = (ValueNode) node).isTextual()) {
unit = TimeUnit.valueOf(valueNode.asText().toUpperCase());
} else {
unit = Duration.DEFAULT_UNIT;
}
return new Duration(duration, unit);
}
@Override
public JSONOptions deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
JsonLocation l = jp.getTokenLocation();
// logger.debug("Reading tree.");
TreeNode n = jp.readValueAsTree();
// logger.debug("Tree {}", n);
if (n instanceof JsonNode) {
return new JSONOptions( (JsonNode) n, l);
} else {
throw new IllegalArgumentException(String.format("Received something other than a JsonNode %s", n));
}
}
@Override
public Tags deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
TreeNode n = jp.getCodec().readTree(jp);
Map<String, String> tags = new HashMap<>();
Iterator<String> namesIter = n.fieldNames();
while(namesIter.hasNext()) {
String field = namesIter.next();
TreeNode child = n.get(field);
if (child instanceof TextNode) {
tags.put(field, ((TextNode) child).asText());
}
}
return new Tags(tags);
}