Java Code Examples for com.fasterxml.jackson.core.TreeNode#get()

The following examples show how to use com.fasterxml.jackson.core.TreeNode#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateJsonConvert.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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;
}
 
Example 2
Source File: MetricStoreTest.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
@Test
public void testJson() throws IOException {
  final MetricStore metricStore = MetricStore.getStore();

  metricStore.getOrCreateMetric(JobMetric.class, "testId");

  final String json = metricStore.dumpMetricToJson(JobMetric.class);

  final ObjectMapper objectMapper = new ObjectMapper();
  final TreeNode treeNode = objectMapper.readTree(json);

  final TreeNode jobMetricNode = treeNode.get("JobMetric");
  assertNotNull(jobMetricNode);

  final TreeNode metricNode = jobMetricNode.get("testId");
  assertNotNull(metricNode);

  final TreeNode fieldNode = metricNode.get("id");
  assertTrue(fieldNode.isValueNode());
}
 
Example 3
Source File: ReadViaCodecTest.java    From jackson-jr with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 4
Source File: ResourceSitePass.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
/**
 * @param jsonString serialized bandwidth specification.
 * @return the bandwidth specification.
 */
static BandwidthSpecification fromJsonString(final String jsonString) {
  final BandwidthSpecification specification = new BandwidthSpecification();
  try {
    final ObjectMapper objectMapper = new ObjectMapper();
    final TreeNode jsonRootNode = objectMapper.readTree(jsonString);
    for (int i = 0; i < jsonRootNode.size(); i++) {
      final TreeNode locationNode = jsonRootNode.get(i);
      final String name = locationNode.get("name").traverse().nextTextValue();
      final int up = locationNode.get("up").traverse().getIntValue();
      final int down = locationNode.get("down").traverse().getIntValue();
      specification.nodeNames.add(name);
      specification.uplinkBandwidth.put(name, up);
      specification.downlinkBandwidth.put(name, down);
    }
  } catch (final IOException e) {
    throw new RuntimeException(e);
  }
  return specification;
}
 
Example 5
Source File: BaseObjectTypeDefinition.java    From conjure with Apache License 2.0 6 votes vote down vote up
@Override
public BaseObjectTypeDefinition deserialize(JsonParser parser, DeserializationContext _ctxt)
        throws IOException {
    TreeNode tree = parser.readValueAsTree();
    if (tree.get("fields") != null) {
        return ObjectTypeDefinition.fromJson(parser, tree);
    } else if (tree.get("values") != null) {
        return EnumTypeDefinition.fromJson(parser, tree);
    } else if (tree.get("alias") != null) {
        return AliasTypeDefinition.fromJson(parser, tree);
    } else if (tree.get("union") != null) {
        return UnionTypeDefinition.fromJson(parser, tree);
    } else if (tree.get("namespace") != null) {
        return ErrorTypeDefinition.fromJson(parser, tree);
    } else {
        throw new SafeIllegalArgumentException(
                "Unrecognized definition, types must have either fields, values or an alias defined.");
    }
}
 
Example 6
Source File: ComponentInstanceDeserializer.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example 7
Source File: KnoxShellTableRowDeserializer.java    From knox with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 8
Source File: TsdbResult.java    From splicer with Apache License 2.0 6 votes vote down vote up
@Override
public Points deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
	TreeNode n = jp.getCodec().readTree(jp);
	Map<String, Object> points = new HashMap<>();
	Iterator<String> namesIter = n.fieldNames();
	while(namesIter.hasNext()) {
		String field = namesIter.next();
		TreeNode child = n.get(field);

		Object o;
		if (child instanceof DoubleNode || child instanceof FloatNode) {
			o = ((NumericNode) child).doubleValue();
		} else if (child instanceof IntNode || child instanceof LongNode) {
			o = ((NumericNode) child).longValue();
		} else {
			throw new MergeException("Unsupported Type, " + child.getClass());
		}

		points.put(field, o);
	}
	return new Points(points);
}
 
Example 9
Source File: PrivateTransaction.java    From web3j with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 10
Source File: PipelineOptionsTranslation.java    From beam with Apache License 2.0 6 votes vote down vote up
/** 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);
  }
}
 
Example 11
Source File: KnoxShellTableRowDeserializer.java    From knox with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 12
Source File: GenerateBatch.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
    TreeNode node = p.readValueAsTree();
    JsonNode include = (JsonNode) node.get(INCLUDE);
    ObjectMapper codec = (ObjectMapper) ctx.getParser().getCodec();

    if (include != null) {
        String ref = include.textValue();
        if (ref != null) {
            File includeFile = scanDir != null ? new File(scanDir, ref) : new File(ref);
            if (includeFile.exists()) {
                // load the file into the tree node and continue parsing as normal
                ((ObjectNode) node).remove(INCLUDE);

                TreeNode includeNode;
                try (JsonParser includeParser = codec.getFactory().createParser(includeFile)) {
                    includeNode = includeParser.readValueAsTree();
                }

                ObjectReader reader = codec.readerForUpdating(node);
                TreeNode updated = reader.readValue(includeNode.traverse());
                JsonParser updatedParser = updated.traverse();
                updatedParser.nextToken();
                return super.deserialize(updatedParser, ctx);
            }
        }
    }

    JsonParser newParser = node.traverse();
    newParser.nextToken();
    return super.deserialize(newParser, ctx);
}
 
Example 13
Source File: KnoxShellTableRowDeserializer.java    From knox with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 14
Source File: TikaTextExtractor.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public ContentAndMetadata deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
    Preconditions.checkState(treeNode.isArray() && treeNode.size() >= 1, "The response should be an array with at least one element");
    Preconditions.checkState(treeNode.get(0).isObject(), "The element should be a Json object");
    ObjectNode node = (ObjectNode) treeNode.get(0);
    return ContentAndMetadata.from(ImmutableList.copyOf(node.fields())
        .stream()
        .collect(Guavate.toImmutableMap(Entry::getKey, entry -> asListOfString(entry.getValue()))));
}
 
Example 15
Source File: DurationSerialization.java    From heroic with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 16
Source File: TsdbResult.java    From splicer with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 17
Source File: Util.java    From incubator-nemo with Apache License 2.0 4 votes vote down vote up
/**
 * Utility method for parsing the resource specification string.
 *
 * @param resourceSpecificationString the input resource specification string.
 * @return the parsed list of resource specifications. The Integer indicates how many of the specified nodes are
 * required, followed by the ResourceSpecification that indicates the specifications of the nodes.
 */
public static List<Pair<Integer, ResourceSpecification>> parseResourceSpecificationString(
  final String resourceSpecificationString) {
  final List<Pair<Integer, ResourceSpecification>> resourceSpecifications = new ArrayList<>();
  try {
    if (resourceSpecificationString.trim().startsWith("[")) {
      final TreeNode jsonRootNode = new ObjectMapper().readTree(resourceSpecificationString);

      for (int i = 0; i < jsonRootNode.size(); i++) {
        final TreeNode resourceNode = jsonRootNode.get(i);
        final int executorNum = resourceNode.path("num").traverse().nextIntValue(1);
        final String type = resourceNode.get("type").traverse().nextTextValue();
        final int capacity = resourceNode.get("capacity").traverse().getIntValue();
        final int memory = resourceNode.get("memory_mb").traverse().getIntValue();
        final OptionalDouble maxOffheapRatio;
        final OptionalInt poisonSec;

        if (resourceNode.path("max_offheap_ratio").traverse().nextToken() == JsonToken.VALUE_NUMBER_FLOAT) {
          maxOffheapRatio = OptionalDouble.of(resourceNode.path("max_offheap_ratio").traverse().getDoubleValue());
        } else {
          maxOffheapRatio = OptionalDouble.empty();
        }

        if (resourceNode.path("poison_sec").traverse().nextToken() == JsonToken.VALUE_NUMBER_INT) {
          poisonSec = OptionalInt.of(resourceNode.path("poison_sec").traverse().getIntValue());
        } else {
          poisonSec = OptionalInt.empty();
        }

        resourceSpecifications.add(
          Pair.of(executorNum, new ResourceSpecification(type, capacity, memory, maxOffheapRatio, poisonSec)));
      }
    } else {
      throw new UnsupportedOperationException("Executor Info file should be a JSON file.");
    }

    return resourceSpecifications;
  } catch (final Exception e) {
    throw new JsonParseException(e);
  }
}
 
Example 18
Source File: UserJsonDeserializer.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
    TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
    return new User(Color.web(favoriteColor.asText()));
}
 
Example 19
Source File: UserCombinedSerializer.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
    TextNode favoriteColor = (TextNode) treeNode.get("favoriteColor");
    return new User(Color.web(favoriteColor.asText()));
}