org.codehaus.jackson.JsonNode类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(12.7k)|赞(0)|评价(0)|浏览(255)

本文整理了Java中org.codehaus.jackson.JsonNode类的一些代码示例,展示了JsonNode类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonNode类的具体详情如下:
包路径:org.codehaus.jackson.JsonNode
类名称:JsonNode

JsonNode介绍

[英]Base class for all JSON nodes, which form the basis of JSON Tree Model that Jackson implements. One way to think of these nodes is to consider them similar to DOM nodes in XML DOM trees.

As a general design rule, most accessors ("getters") are included in this base class, to allow for traversing structure without type casts. Most mutators, however, need to be accessed through specific sub-classes (such as org.codehaus.jackson.node.ObjectNode and org.codehaus.jackson.node.ArrayNode). This seems sensible because proper type information is generally available when building or modifying trees, but less often when reading a tree (newly built from parsed JSON content).

Actual concrete sub-classes can be found from package org.codehaus.jackson.node, which is in 'mapper' jar (whereas this class is in 'core' jar, since it is declared as nominal type for operations in ObjectCodec)
[中]所有JSON节点的基类,构成Jackson实现的JSON树模型的基础。考虑这些节点的一种方法是考虑它们与XML DOM树中的DOM节点类似。
作为一般设计规则,大多数访问器(“getter”)都包含在这个基类中,以允许在没有类型转换的情况下遍历结构。然而,大多数变异子需要通过特定的子类(例如org.codehaus.jackson.node.ObjectNodeorg.codehaus.jackson.node.ArrayNode来访问。这似乎是合理的,因为在构建或修改树时,通常可以使用适当的类型信息,但在读取树(从解析的JSON内容新构建)时,这种情况不太常见。
实际的具体子类可以从包组织中找到。科德豪斯。杰克逊。节点,它位于“mapper”jar中(而这个类位于“core”jar中,因为它在ObjectCodec中被声明为操作的标称类型)

代码示例

代码示例来源:origin: neo4j/neo4j

private void assertQueryGetsValue( ServerControls server, String query, long value ) throws Throwable
{
  HTTP.Response response = HTTP.POST( server.httpURI().resolve( "db/data/transaction/commit" ).toString(),
      quotedJson( "{ 'statements': [ { 'statement': '" + query + "' } ] }" ) );
  assertEquals( "[]", response.get( "errors" ).toString() );
  JsonNode result = response.get( "results" ).get( 0 );
  assertEquals( "value", result.get( "columns" ).get( 0 ).asText() );
  assertEquals( value, result.get( "data" ).get( 0 ).get( "row" ).get( 0 ).asLong() );
}

代码示例来源:origin: kaaproject/kaa

if (!object.has(TYPE) || !object.get(TYPE).isTextual()
  || !object.get(TYPE).getTextValue().equals("record")) {
 throw new IllegalArgumentException("The data provided is not a record!");
if (!object.has(NAMESPACE) || !object.get(NAMESPACE).isTextual()) {
 throw new IllegalArgumentException("No namespace specified!");
} else if (!object.has(NAME) || !object.get(NAME).isTextual()) {
 throw new IllegalArgumentException("No name specified!");
} else {
 fqn = object.get(NAMESPACE).getTextValue() + "." + object.get(NAME).getTextValue();
if (!object.has(VERSION) || !object.get(VERSION).isInt()) {
 object.put(VERSION, 1);
schema.setVersion(object.get(VERSION).asInt());
if (!object.has(DEPENDENCIES)) {
 schema.setDependencySet(dependencies);
} else if (!object.get(DEPENDENCIES).isArray()) {
 throw new IllegalArgumentException("Illegal dependencies format!");
} else {
 for (JsonNode child : object.get(DEPENDENCIES)) {
  if (!child.isObject() || !child.has(FQN) || !child.get(FQN).isTextual()
    || !child.has(VERSION) || !child.get(VERSION).isInt()) {
   throw new IllegalArgumentException("Illegal dependency format!");
  } else {
   String dependencyFqn = child.get(FQN).asText();
   int dependencyVersion = child.get(VERSION).asInt();

代码示例来源:origin: org.codehaus.jackson/jackson-mapper-asl

@Override
public int getIntValue() throws IOException, JsonParseException {
  return currentNumericNode().getIntValue();
}

代码示例来源:origin: org.apache.avro/avro

private String parseDocNode(JsonNode json) {
 JsonNode nameNode = json.get("doc");
 if (nameNode == null) return null;                 // no doc defined
 return nameNode.getTextValue();
}

代码示例来源:origin: org.apache.avro/avro

/**
 * Returns the value of the named, string-valued property in this schema.
 * Returns <tt>null</tt> if there is no string-valued property with that name.
 */
public String getProp(String name) {
 JsonNode value = getJsonProp(name);
 return value != null && value.isTextual() ? value.getTextValue() : null;
}

代码示例来源:origin: kaaproject/kaa

/**
  * Removes UUIDs from a json tree.
  *
  * @param json json tree node
  */
 public static void removeUuids(JsonNode json) {
  boolean containerWithId = json.isContainerNode() && json.has(UUID_FIELD);
  boolean isArray = json.isArray();
  boolean childIsNotArray = !(json.size() == 1 && json.getElements().next().isArray());

  if (containerWithId && !isArray && childIsNotArray) {
   ((ObjectNode) json).remove(UUID_FIELD);
  }

  for (JsonNode node : json) {
   if (node.isContainerNode()) {
    removeUuids(node);
   }
  }
 }
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldFixturesWork() throws Exception
{
  // Given the rule in the beginning of this class
  // When I run this test
  // Then
  HTTP.Response response = HTTP.POST( neo4j.httpURI().toString() + "db/data/transaction/commit",
      quotedJson( "{'statements':[{'statement':'MATCH (n:User) RETURN n'}]}" ) );
  assertThat( response.get( "results" ).get( 0 ).get( "data" ).size(), equalTo( 2 ) );
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldWriteNestedMaps() throws Exception
{
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  JsonGenerator json = new JsonFactory( new Neo4jJsonCodec() ).createJsonGenerator( out );
  JsonNode rest = serialize( out, json, new RestRepresentationWriter( URI.create( "localhost" ) ) );
  MatcherAssert.assertThat( rest.size(), equalTo( 1 ) );
  JsonNode firstCell = rest.get( 0 );
  MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).size(), is( 2 ) );
  MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).get( 0 ).asBoolean(), is( true ) );
  MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).get( 1 ).get( "three" ).asInt(), is( 42 ) );
}

代码示例来源:origin: neo4j/neo4j

private void assertQueryGetsError( ServerControls server, String query, String error ) throws Throwable
  {
    HTTP.Response response = HTTP.POST( server.httpURI().resolve( "db/data/transaction/commit" ).toString(),
        quotedJson( "{ 'statements': [ { 'statement': '" + query + "' } ] }" ) );

    assertThat( response.get( "errors" ).toString(), containsString( error ) );
  }
}

代码示例来源:origin: neo4j/neo4j

private void assertDBConfig( ServerControls server, String expected, String key ) throws JsonParseException
{
  JsonNode beans = HTTP.GET(
      server.httpURI().toString() + "db/manage/server/jmx/domain/org.neo4j/" ).get( "beans" );
  JsonNode configurationBean = findNamedBean( beans, "Configuration" ).get( "attributes" );
  boolean foundKey = false;
  for ( JsonNode attribute : configurationBean )
  {
    if ( attribute.get( "name" ).asText().equals( key ) )
    {
      assertThat( attribute.get( "value" ).asText(), equalTo( expected ) );
      foundKey = true;
      break;
    }
  }
  if ( !foundKey )
  {
    fail( "No config key '" + key + "'." );
  }
}

代码示例来源:origin: neo4j/neo4j

@Test
public void txEndpointShouldReplyWithHttpsWhenItReturnsURLs() throws Exception
{
  startServer();
  String baseUri = server.baseUri().toString();
  HTTP.Response response = POST( baseUri + "db/data/transaction", quotedJson( "{'statements':[]}" ) );
  assertThat( response.location(), startsWith( baseUri ) );
  assertThat( response.get( "commit" ).asText(), startsWith( baseUri ) );
}

代码示例来源:origin: apache/incubator-gobblin

@Test
 public void testRecord() throws DataConversionException, IOException {
  Iterable<String> records = converter.convertRecord(null, sampleRecord, state);
  Iterator<String> recordIt = records.iterator();
  ObjectMapper objectMapper = new ObjectMapper();

  String record = recordIt.next();

  Assert.assertFalse(recordIt.hasNext());
  JsonNode parsedRecord = objectMapper.readValue(record, JsonNode.class);

  Assert.assertEquals(parsedRecord.get("field1").getTextValue(), sampleRecord.get("field1").toString());
 }
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldHandleMapParametersCorrectly() throws Exception
{
  Response response = http.POST(
      "db/data/transaction/commit",
      quotedJson("{ 'statements': [ { 'statement': " +
          "'WITH {map} AS map RETURN map[0]', 'parameters':{'map':[{'index':0,'name':'a'},{'index':1,'name':'b'}]} } ] }"));
  // then
  assertThat( response.status(), equalTo( 200 ) );
  JsonNode data = response.get( "results" ).get( 0 );
  JsonNode row = data.get( "data" ).get( 0 ).get( "row" );
  assertThat( row.size(), equalTo( 1 ) );
  assertThat( row.get(0).get("index").asInt(), equalTo( 0 ) );
  assertThat( row.get(0).get("name").asText(), equalTo( "a" ) );
  assertThat( response.get( "errors" ).size(), equalTo( 0 ) );
}

代码示例来源:origin: voldemort/voldemort

Schema.Type fieldType = schema.getType();
String expectedVal = null;
switch(fieldType) {
  case NULL:
    if(!defaultJson.isNull()) {
      expectedVal = "null";
    if(!defaultJson.isBoolean()) {
      expectedVal = "boolean";
    if(!defaultJson.isInt()) {
      expectedVal = "int";
    if(!defaultJson.isInt() && !defaultJson.isLong()) {
      expectedVal = "long";
  case FLOAT:
  case DOUBLE:
    if(!defaultJson.isNumber()) {
      expectedVal = "number";
    if(defaultJson.isTextual()) {
      break;
    break;
  case STRING:
    if(!defaultJson.isTextual()) {
      expectedVal = "string";

代码示例来源:origin: org.apache.avro/avro

} else if (jsonNode.isNull()) {
 return JsonProperties.NULL_VALUE;
} else if (jsonNode.isBoolean()) {
 return jsonNode.asBoolean();
} else if (jsonNode.isInt()) {
 if (schema == null || schema.getType().equals(Schema.Type.INT)) {
  return jsonNode.asInt();
 } else if (schema.getType().equals(Schema.Type.LONG)) {
  return jsonNode.asLong();
} else if (jsonNode.isLong()) {
 return jsonNode.asLong();
} else if (jsonNode.isDouble()) {
 if (schema == null || schema.getType().equals(Schema.Type.DOUBLE)) {
  return jsonNode.asDouble();
 } else if (schema.getType().equals(Schema.Type.FLOAT)) {
  return (float) jsonNode.asDouble();
} else if (jsonNode.isTextual()) {
  return jsonNode.asText();
  try {
   return jsonNode.getTextValue().getBytes(BYTES_CHARSET);
  } catch (UnsupportedEncodingException e) {
   throw new AvroRuntimeException(e);
} else if (jsonNode.isArray()) {
 List l = new ArrayList();

代码示例来源:origin: neo4j/neo4j

assertThat( response.status(), equalTo( 200 ) );
JsonNode data = response.get( "results" ).get( 0 ).get( "data" );
assertTrue( "data is a list", data.isArray() );
assertEquals( "one entry", initialData + 1, data.size() );
JsonNode entry = data.get( 0 );
assertTrue( "entry has row", entry.has( "row" ) );
assertTrue( "entry has graph", entry.has( "graph" ) );
JsonNode nodes = entry.get( "graph" ).get( "nodes" );
JsonNode rels = entry.get( "graph" ).get( "relationships" );
assertTrue( "nodes is a list", nodes.isArray() );
assertTrue( "relationships is a list", rels.isArray() );
assertEquals( "one node", 1, nodes.size() );
assertEquals( "no relationships", 0, rels.size() );
Set<String> labels = new HashSet<>();
for ( JsonNode node : nodes.get( 0 ).get( "labels" ) )
  labels.add( node.getTextValue() );

代码示例来源:origin: neo4j/neo4j

@Override
protected boolean matchesSafely( HTTP.Response response )
{
  try
  {
    JsonNode list = TransactionMatchers.getJsonNodeWithName( response, "rest" ).iterator().next();
    assertThat( list.get( 0 ).get( "metadata" ).get( "deleted" ).asBoolean(), equalTo( Boolean.TRUE ) );
    assertThat( list.get( 1 ).get( "someKey" ).get( "metadata" ).get( "deleted" ).asBoolean(),
        equalTo( Boolean.TRUE ) );
    return true;
  }
  catch ( JsonParseException e )
  {
    return false;
  }
}

代码示例来源:origin: org.apache.avro/avro

public static void encode(Encoder e, Schema s, JsonNode n)
 throws IOException {
 switch (s.getType()) {
 case RECORD:
  for (Field f : s.getFields()) {
   String name = f.name();
   JsonNode v = n.get(name);
   if (v == null) {
    v = f.defaultValue();
  e.writeEnum(s.getEnumOrdinal(n.getTextValue()));
  break;
 case ARRAY:
  e.writeArrayStart();
  e.setItemCount(n.size());
 case MAP:
  e.writeMapStart();
  e.setItemCount(n.size());
  Schema v = s.getValueType();
  for (Iterator<String> it = n.getFieldNames(); it.hasNext();) {
   e.startItem();
   String key = it.next();
   e.writeString(key);
   encode(e, v, n.get(key));
  break;
 case FIXED:
  if (!n.isTextual())

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldReturnReadOnlyStatusWhenCreatingNodes() throws Exception
{
  // Given
  HTTP.Response response = http.POST( "db/data/transaction/commit",
      quotedJson( "{ 'statements': [ { 'statement': 'CREATE (node)' } ] }" ) );
  // Then
  JsonNode error = response.get( "errors" ).get( 0 );
  String code = error.get( "code" ).asText();
  String message = error.get( "message" ).asText();
  assertEquals( "Neo.ClientError.General.ForbiddenOnReadOnlyDatabase", code );
  assertThat( message, containsString( "This is a read only Neo4j instance" ) );
}

代码示例来源:origin: org.apache.avro/avro

private static boolean isValidDefault(Schema schema, JsonNode defaultValue) {
 if (defaultValue == null)
  return false;
 switch (schema.getType()) {
 case STRING:
 case BYTES:
 case ENUM:
 case FIXED:
  return defaultValue.isTextual();
 case INT:
 case LONG:
 case FLOAT:
 case DOUBLE:
  return defaultValue.isNumber();
 case BOOLEAN:
  return defaultValue.isBoolean();
 case NULL:
  return defaultValue.isNull();
 case ARRAY:
  if (!defaultValue.isArray())
   return false;
  for (JsonNode element : defaultValue)
   if (!isValidDefault(schema.getElementType(), element))
    return false;
  return true;
 case MAP:
  if (!defaultValue.isObject())
   return false;
  for (JsonNode value : defaultValue)

相关文章