下面列出了com.fasterxml.jackson.core.ObjectCodec# treeToValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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 Node deserialize(JsonParser parser, DeserializationContext ctxt) 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);
String classes = codec.treeToValue(tree.path(FieldName.CLASSES), String.class);
Map<String, String> attributes = codec.treeToValue(tree.path(FieldName.OTHER), Map.class);
attributes.put(FieldName.ID, id);
attributes.put(FieldName.CLASS, classes);
return new NodeBuilder()
.setTag(tag)
.setIndex(index)
.addContent(innerText)
.setAttributes(attributes)
.build();
}
@Override
public StateActionValue deserialize(JsonParser p, DeserializationContext context) throws IOException {
final StateActionValue.Builder builder = StateActionValue.builder();
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
if (node.has("type")) {
builder.setBlockElementType(node.get("type").asText());
}
if (node.has("value")) {
builder.setBlockElementValue(node.get("value").asText());
} else if (node.has("selected_option")) {
final JsonNode selectedOption = node.get("selected_option");
final Option option = codec.treeToValue(selectedOption, Option.class);
builder.setBlockElementValue(option);
} else if (node.has("selected_date")) {
builder.setBlockElementValue(LocalDate.parse(node.get("selected_date").asText()));
}
return builder.build();
}
@Override
public BlockElementAction deserialize(JsonParser p, DeserializationContext context) throws IOException {
BlockElementAction.Builder builder = BlockElementAction.builder();
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
builder.setBlockId(node.get(BLOCK_ID_FIELD).asText());
// select menu elements don't send a value field, they send a `selected_option` object that has a value field
if (node.has("selected_option")) {
builder.setSelectedValue(readOptionalString(node.get("selected_option"), VALUE_FIELD));
} else {
builder.setSelectedValue(readOptionalString(node, VALUE_FIELD));
}
// datepickers don't have a value field, but they have a "selected_date" field with a LocalDate-style string
if (node.has("selected_date")) {
readOptionalString(node, SELECTED_DATE_FIELD)
.map(LocalDate::parse)
.ifPresent(builder::setSelectedDate);
}
builder.setActionTs(readOptionalString(node, ACTION_TS_FIELD));
BlockElement element = codec.treeToValue(node, BlockElement.class);
builder.setElement(element);
return builder.build();
}
@Override
public SourceForgeArticle deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
JsonNode attachmentsNode = node.path("attachments");
SourceForgeAttachment[] attachments = oc.treeToValue(attachmentsNode, SourceForgeAttachment[].class);
SourceForgeArticle article = new SourceForgeArticle();
article.setArticleNumber(articleNumber++);
article.setSubject(getText(node, "subject"));
article.setText(getText(node, "text"));
article.setUser(getText(node,"author"));
article.setAttachments(attachments);
article.setArticleId(getText(node, "slug"));
article.setDate(getDate(node, SourceForgeConstants.RESPONSE_DATE_FORMATTER, "timestamp"));
article.setUpdateDate(getDate(node, SourceForgeConstants.RESPONSE_DATE_FORMATTER, "last_edited"));
article.setReferences(new String[0]);
return article;
}
@Override
public SourceForgeTopic deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
node = node.get("topic");
SourceForgeTopic topic = new SourceForgeTopic();
String topicId = getText(node, "_id");
topic.setTopicId(topicId);
topic.setDiscussionId(getText(node, "discussion_id"));
topic.setSubject(getText(node, "subject"));
JsonNode articlesNode = node.path("posts");
SourceForgeArticle[] articles = oc.treeToValue(articlesNode, SourceForgeArticle[].class);
for (SourceForgeArticle article: articles) {
article.setMessageThreadId(topicId);
topic.getArticles().add(article);
}
return topic;
}
@Override
public SourceForgeComment deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
JsonNode attachmentsNode = node.path("attachments");
SourceForgeAttachment[] attachments = oc.treeToValue(attachmentsNode, SourceForgeAttachment[].class);
SourceForgeComment comment = new SourceForgeComment();
comment.setSubject(getText(node, "subject"));
comment.setText(getText(node, "text"));
comment.setCreator(getText(node,"author"));
comment.setAttachments(attachments);
comment.setCommentId(getText(node, "slug"));
comment.setCreationTime(getDate(node, SourceForgeConstants.RESPONSE_DATE_FORMATTER, "timestamp"));
comment.setUpdateDate(getDate(node, SourceForgeConstants.RESPONSE_DATE_FORMATTER, "last_edited"));
return comment;
}
@Override
public RedmineComment deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
RedmineComment comment = new RedmineComment();
comment.setCommentId(getText(node, "id"));
comment.setText(getText(node, "notes"));
comment.setCreationTime(getDate(node, context, "created_on"));
comment.setCreator(getText(node, "user", "name"));
comment.setCreatorId(getInteger(node, "user", "id") );
JsonNode detailsNode = node.get("details");
if (null != detailsNode) {
RedmineCommentDetails[] details = oc.treeToValue(detailsNode,
RedmineCommentDetails[].class);
for (RedmineCommentDetails d : details) {
comment.getDetails().add(d);
}
}
return comment;
}
@Override
public T deserialize( JsonParser p, DeserializationContext ctxt ) throws IOException
{
final ObjectCodec oc = p.getCodec();
final JsonNode jsonNode;
if ( oc instanceof XmlMapper )
{
jsonNode = createJsonNode( p, ctxt );
return objectMapper.treeToValue( jsonNode, overrideClass );
}
else
{
jsonNode = oc.readTree( p );
// original object mapper must be used since it may have different serialization settings
return oc.treeToValue( jsonNode, overrideClass );
}
}
/**
* {@inheritDoc}
*/
@Override
public CertPath deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
ObjectCodec oc = p.getCodec();
ArrayNode node = oc.readTree(p);
List<Certificate> list = new ArrayList<>();
for (JsonNode item : node) {
X509Certificate certificate = oc.treeToValue(item, X509Certificate.class);
list.add(certificate);
}
return CertificateUtil.generateCertPath(list);
}
@SuppressWarnings("unchecked")
public T deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
ObjectCodec objectCodec = jsonParser.getCodec();
ObjectNode objectNode = objectCodec.readTree(jsonParser);
String typeValue = null;
JsonNode type = objectNode.get(TYPE_PROPERTY);
if (type != null) {
typeValue = type.asText();
if (STRING_PROPERTY_VALUE.equals(typeValue)) {
if (objectNode.get(ENUM_PROPERTY) != null) {
typeValue = "enum";
}
}
} else {
if (objectNode.get(REF_PROPERTY) != null) {
typeValue = "ref";
}
}
if (typeValue == null) {
throw new JsonParseException(jsonParser, "Unknown object type.");
}
DeserializationConfig config = context.getConfig();
AnnotatedClass annotatedClass =
AnnotatedClassResolver.resolveWithoutSuperTypes(config, handledType());
List<NamedType> subtypes = config.getAnnotationIntrospector().findSubtypes(annotatedClass);
for (NamedType namedType : subtypes) {
if (typeValue.equals(namedType.getName())) {
return (T) objectCodec.treeToValue(objectNode, namedType.getType());
}
}
throw new JsonParseException(jsonParser, "Unknown object type " + typeValue + ".");
}
@Override
public BlockOrAttachment deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
ObjectCodec codec = jsonParser.getCodec();
JsonNode node = codec.readTree(jsonParser);
if (node.has(TYPE_FIELD)) {
return codec.treeToValue(node, Block.class);
} else {
return codec.treeToValue(node, Attachment.class);
}
}
@Override
public ValueImpl deserialize(JsonParser jsonParser,
DeserializationContext ctxt) throws IOException {
ObjectCodec mapper = jsonParser.getCodec();
JsonNode root = mapper.readTree(jsonParser);
Class<? extends ValueImpl> valueClass = getValueClass(root, jsonParser);
return mapper.treeToValue(root, valueClass);
}
@Override
public ImageBlockOrText deserialize(JsonParser p, DeserializationContext context) throws IOException {
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
String type = node.get(TYPE_FIELD).asText();
if (Image.TYPE.equals(type)) {
return codec.treeToValue(node, Image.class);
}
return codec.treeToValue(node, Text.class);
}
@Override
public SlackEvent deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
SlackEventType type = SlackEventType.get(node.get(TYPE_FIELD).asText());
// Messages can have subtypes that we need to handle
if (type == SlackEventType.MESSAGE && node.has(SUBTYPE_FIELD)) {
SlackMessageSubtype subtype = SlackMessageSubtype.get(node.get(SUBTYPE_FIELD).asText());
return codec.treeToValue(node, subtype.getMessageClass());
}
return codec.treeToValue(node, type.getEventClass());
}
Object deserialize(JsonNode node, String fieldName, Class targetClass, DeserializationContext ctxt) throws IOException {
final String type = getFieldClassFQN(targetClass, type());
try {
final Class<?> fieldClass = Thread.currentThread().getContextClassLoader().loadClass(type);
// check if we have embedded interface field, in which case the target field won't be declared on the target
// class but rather on the class pointed to by the field
// e.g. given:
// trafficPolicy:
// loadBalancer:
// simple: ROUND_ROBIN
// LoadBalancerSettings (loadBalancer field) doesn't have a `simple` field, this is just an unwrapped
// implementation of the LbPolicy interface, so we need to check the type of the `simple` field and deserialize
// the node as an instance of that class instead.
final Optional<Field> field = getField(targetClass, fieldName);
final ObjectCodec codec = ctxt.getParser().getCodec();
if (field.isPresent()) {
// if field is present, deserialize it with the specified field class
return codec.treeToValue(getTargetNode(node, fieldName), fieldClass);
} else {
// otherwise, get the type of the field
final Class<?> childFieldClass = fieldClass.getDeclaredField(fieldName).getType();
// deserialize the field using that new class
Object childObject = codec.treeToValue(getTargetNode(node, fieldName), childFieldClass);
// finally, build the instance assigning it the deserialized child field
// NOTE: this only works if the interface implementation only has one field (since otherwise, there won't
// be a single-argument constructor accepting an instance of the newly created instance
return fieldClass.getDeclaredConstructor(childFieldClass).newInstance(childObject);
}
} catch (ClassNotFoundException | JsonProcessingException | NoSuchFieldException | NoSuchMethodException |
InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Unsupported type '" + type + "' for field '" + fieldName + "' on '" + targetClass.getName() + "' class", e);
}
}
@Override
public LSServerPostMapValuesList deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
ObjectCodec oc = jp.getCodec();
JsonNode node = oc.readTree(jp);
List<LSServerPostMapValues> mappersList = new ArrayList<>();
for (JsonNode childNode : node) {
List<LSServerMapField> mappers = new ArrayList<>();
for (Iterator<Map.Entry<String, JsonNode>> i = childNode.fields(); i.hasNext();) {
Map.Entry<String, JsonNode> mapperData = i.next();
String mapperType = mapperData.getKey();
JsonNode mapperProperties = mapperData.getValue();
switch (mapperType) {
case "map_date" :
LSServerMapDate mapDate = oc.treeToValue(mapperProperties, LSServerMapDate.class);
mappers.add(mapDate);
break;
case "map_field_name" :
LSServerMapFieldName mapFieldName = oc.treeToValue(mapperProperties, LSServerMapFieldName.class);
mappers.add(mapFieldName);
break;
case "map_field_value" :
LSServerMapFieldValue mapFieldValue = oc.treeToValue(mapperProperties, LSServerMapFieldValue.class);
mappers.add(mapFieldValue);
break;
case "map_field_copy" :
LSServerMapFieldCopy mapFieldCopy = oc.treeToValue(mapperProperties, LSServerMapFieldCopy.class);
mappers.add(mapFieldCopy);
break;
case "map_anonymize" :
LSServerMapFieldAnonymize mapAnonymize = oc.treeToValue(mapperProperties, LSServerMapFieldAnonymize.class);
mappers.add(mapAnonymize);
break;
}
}
LSServerPostMapValues lsServerPostMapValues = new LSServerPostMapValues();
lsServerPostMapValues.setMappers(mappers);
mappersList.add(lsServerPostMapValues);
}
LSServerPostMapValuesList lsServerPostMapValuesList = new LSServerPostMapValuesList();
lsServerPostMapValuesList.setMappersList(mappersList);
return lsServerPostMapValuesList;
}
@Override
public StateBlock deserialize(JsonParser p, DeserializationContext context) throws IOException {
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
return codec.treeToValue(node.get(VALUES_FIELD), StateBlock.class);
}
@Override
public SourceForgeTicket deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
node = node.get("ticket");
SourceForgeTicket ticket = new SourceForgeTicket();
JsonNode attachmentsNode = node.path("attachments");
SourceForgeAttachment[] attachments = oc.treeToValue(attachmentsNode, SourceForgeAttachment[].class);
JsonNode labelsNode = node.path("labels");
String[] labels = oc.treeToValue(labelsNode, String[].class);
String bugId = getText(node, "ticket_num");
ticket.setBugId(bugId);
ticket.setAssignee(getText(node, "assigned_to"));
ticket.setAssigneeId(getText(node, "assigned_to_id"));
ticket.setAttachments(attachments);
ticket.setCommentsUrl(getText(node, "discussion_thread_url"));
ticket.setCreationTime(getDate(node, SourceForgeConstants.RESPONSE_DATE_FORMATTER, "created_date"));
ticket.setCreator(getText(node, "reported_by"));
ticket.setCreatorId(getText(node, "reported_by_id"));
ticket.setDescription(getText(node, "description"));
ticket.setInternalId(getText(node, "_id"));
ticket.setLabels(labels);
ticket.setPrivate(getBoolean(node, "private"));
ticket.setStatus(getText(node, "status"));
ticket.setSummary(getText(node, "summary"));
ticket.setUpdateDate(getDate(node, SourceForgeConstants.RESPONSE_DATE_FORMATTER, "mod_date"));
ticket.setVotesDown(getInteger(node, "votes_down"));
ticket.setVotesUp(getInteger(node, "votes_up"));
JsonNode commentsNode = node.path("discussion_thread").path("posts");
SourceForgeComment[] comments = oc.treeToValue(commentsNode, SourceForgeComment[].class);
for (SourceForgeComment comment: comments) {
comment.setBugId(bugId);
ticket.getComments().add(comment);
}
return ticket;
}
@Override
public RedmineIssue deserialize(JsonParser parser,
DeserializationContext context) throws IOException,
JsonProcessingException {
ObjectCodec oc = parser.getCodec();
JsonNode node = oc.readTree(parser);
RedmineIssue issue = new RedmineIssue();
String bugId = getText(node, "id");
issue.setBugId(bugId);
issue.setCategory(getText(node, "category", "name"));
issue.setCategoryId(getInteger(node, "category", "id"));
issue.setCreationTime(getDate(node, context, "created_on"));
issue.setCreator(getText(node, "author", "name"));
issue.setCreatorId(getInteger(node, "author", "id"));
issue.setDescription(getText(node, "description"));
issue.setPriority(getText(node, "priority", "name"));
issue.setPriorityId(getInteger(node, "priority", "id"));
issue.setProject(getText(node, "project", "name"));
issue.setProjectId(getInteger(node, "project", "id"));
issue.setStatus(getText(node, "status", "name"));
issue.setStatusId(getInteger(node, "status", "id"));
issue.setSubject(getText(node, "subject"));
issue.setTracker(getText(node, "tracker", "name"));
issue.setTrackerId(getInteger(node, "tracker", "id"));
issue.setUpdateDate(getDate(node, context, "updated_on"));
JsonNode commentsNode = node.get("journals");
if (null != commentsNode) {
RedmineComment[] comments = oc.treeToValue(commentsNode,
RedmineComment[].class);
for (RedmineComment comment : comments) {
issue.getComments().add(comment);
comment.setBugId(bugId);
}
}
return issue;
}