当前位置: 首页>>代码示例>>Java>>正文


Java JsonNode类代码示例

本文整理汇总了Java中com.fasterxml.jackson.databind.JsonNode的典型用法代码示例。如果您正苦于以下问题:Java JsonNode类的具体用法?Java JsonNode怎么用?Java JsonNode使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonNode类属于com.fasterxml.jackson.databind包,在下文中一共展示了JsonNode类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: serializeClickActionLineGraphics_resultJsonHasClickAction

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@Test
public void serializeClickActionLineGraphics_resultJsonHasClickAction() throws IOException {
  //when
  Line line = new Line();
  line.onClick(
      new GraphicsActionListener() {
        @Override
        public void execute(GraphicsActionObject actionObject) {}
      });
  graphicsSerializer.serialize(line, jgen, new DefaultSerializerProvider.Impl());
  jgen.flush();
  //then
  JsonNode actualObj = mapper.readTree(sw.toString());
  Assertions.assertThat(actualObj.has("hasClickAction")).isTrue();
  Assertions.assertThat(actualObj.get("hasClickAction").asBoolean()).isTrue();
}
 
开发者ID:twosigma,项目名称:beaker-notebook-archive,代码行数:17,代码来源:GraphicsSerializerTest.java

示例2: create

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
public static Result create() {
    // Get the form from the request
    Form<Record> form = Form.form(Record.class,Record.creation.class).bindFromRequest();
    // Validate errors
    if(form.hasErrors()) {
        return badRequest(form.errorsAsJson());
    }
    // Get the object from the form
    Record object = form.get();
    // Create the object in db
    Ebean.beginTransaction();
    try {
        Record.create(object);
        JsonNode jsonObject = object.jsonSerialization();
        Ebean.commitTransaction();
        return created(jsonObject);
    } catch (Exception e) {
        appLogger.error(Messages.get("Error creating object"), e);
        return internalServerError("Error creating object");
    } finally {
        Ebean.endTransaction();
    }
}
 
开发者ID:ejesposito,项目名称:CS6310O01,代码行数:24,代码来源:Records.java

示例3: testExtractSuccess

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@Test
@SuppressWarnings("resource")
public void testExtractSuccess() throws Exception {
    //Read file into a string
    File sampleFile = new File(getClass().getResource("/sample-aem-credentials.json").getFile());
    String sampleFileContent = new Scanner(sampleFile).useDelimiter("\\Z").next();
    
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(sampleFileContent);
    
    AemCredentials aemCredentials = CredentialsExtractor.extractAemCredentials(sampleFileContent);
    
    assertThat(aemCredentials.getOrchestratorCredentials().getUserName(), 
        equalTo(CredentialsExtractor.ORCHESTRATOR_USER));
    assertThat(aemCredentials.getOrchestratorCredentials().getPassword(), 
        equalTo(root.path(CredentialsExtractor.ORCHESTRATOR_USER).asText()));
    
    assertThat(aemCredentials.getReplicatorCredentials().getUserName(), 
        equalTo(CredentialsExtractor.REPLICATOR_USER));
    assertThat(aemCredentials.getReplicatorCredentials().getPassword(), 
        equalTo(root.path(CredentialsExtractor.REPLICATOR_USER).asText()));
}
 
开发者ID:shinesolutions,项目名称:aem-orchestrator,代码行数:23,代码来源:CredentialsExtractorTest.java

示例4: testcreatePageSection

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@Test
public void testcreatePageSection() {
  PowerMockito.mockStatic(RequestInterceptor.class);
  when( RequestInterceptor.verifyRequestData(Mockito.anyObject()) ).thenReturn("{userId} uuiuhcf784508 8y8c79-fhh");
  Map<String , Object> requestMap = new HashMap<>();
  Map<String , Object> innerMap = new HashMap<>();
  innerMap.put("name" , "page1");
  innerMap.put("sectionDataType" , "section01");
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/section/create").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:18,代码来源:PageControllerTest.java

示例5: listSearchTypes

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@Test
public void listSearchTypes() throws Exception
{
	JsonNode results = getEntity(context.getBaseUrl() + "api/search/myresources", getToken());
	List<String> subSearches = Lists.newArrayList();
	for( JsonNode result : results )
	{
		subSearches.add(result.get("id").asText());
	}

	ArrayList<String> expected = Lists.newArrayList("published", "draft", "archived", "all", "modqueue");
	for( String name : expected )
	{
		assertTrue(subSearches.contains(name), "Should contain '" + name + ", " + subSearches);
	}
}
 
开发者ID:equella,项目名称:Equella,代码行数:17,代码来源:MyResourcesApiTest.java

示例6: processOvsdbMessage

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
/**
 * Processes an JsonNode message received on the channel.
 *
 * @param jsonNode The OvsdbJsonRpcHandler that received the message
 */
private void processOvsdbMessage(JsonNode jsonNode) {

    log.debug("Handle ovsdb message");

    if (jsonNode.has("result")) {

        log.debug("Handle ovsdb result");
        ovsdbProviderService.processResult(jsonNode);

    } else if (jsonNode.hasNonNull("method")) {

        log.debug("Handle ovsdb request");
        if (jsonNode.has("id")
                && !Strings.isNullOrEmpty(jsonNode.get("id").asText())) {
            ovsdbProviderService.processRequest(jsonNode);
        }

    }
    return;
}
 
开发者ID:shlee89,项目名称:athena,代码行数:26,代码来源:OvsdbJsonRpcHandler.java

示例7: createRouter

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createRouter(final InputStream input) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode subnode = mapper.readTree(input);
        Collection<Router> routers = createOrUpdateByInputStream(subnode);

        Boolean result = nullIsNotFound((get(RouterService.class)
                .createRouters(routers)), CREATE_FAIL);
        if (!result) {
            return Response.status(CONFLICT).entity(CREATE_FAIL).build();
        }
        return Response.status(CREATED).entity(result.toString()).build();

    } catch (Exception e) {
        return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
    }
}
 
开发者ID:shlee89,项目名称:athena,代码行数:21,代码来源:RouterWebResource.java

示例8: validate

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
public void validate(T object, ValidationResults results, Set<Class<? extends JsonNode>> allowedNodeTypes) {
	JsonOverlay<?> overlay = (JsonOverlay<?>) object;
	JsonNode json = overlay.toJson();
	boolean isValidJsonType = false;
	for (Class<? extends JsonNode> type : allowedNodeTypes) {
		if (type.isAssignableFrom(json.getClass())) {
			isValidJsonType = true;
			break;
		}
	}
	isValidJsonType = isValidJsonType || json.isMissingNode();
	if (!isValidJsonType) {
		results.addError(m.msg("WrongTypeJson|Property bound to incompatible JSON Node type", json.getNodeType(),
				allowedNodeTypes));
	}
}
 
开发者ID:networknt,项目名称:openapi-parser,代码行数:17,代码来源:OverlayValidator.java

示例9: createBatch

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
/**
 * This method will add a new batch for a particular course.
 * 
 * @return Promise<Result>
 */
public Promise<Result> createBatch() {

  try {
    JsonNode requestData = request().body().asJson();
    ProjectLogger.log("create new batch request data=" + requestData, LoggerEnum.INFO.name());
    Request reqObj = (Request) mapper.RequestMapper.mapRequest(requestData, Request.class);
    RequestValidator.validateCreateBatchReq(reqObj);
    reqObj.setOperation(ActorOperations.CREATE_BATCH.getValue());
    reqObj.setRequestId(ExecutionContext.getRequestId());
    reqObj.setEnv(getEnvironment());
    HashMap<String, Object> innerMap = new HashMap<>();
    if (!ProjectUtil.isStringNullOREmpty((String) reqObj.getRequest().get(JsonKey.BATCH_ID))) {
      reqObj.getRequest().put(JsonKey.ID, reqObj.getRequest().get(JsonKey.BATCH_ID));
      reqObj.getRequest().remove(JsonKey.BATCH_ID);
    }
    innerMap.put(JsonKey.BATCH, reqObj.getRequest());
    innerMap.put(JsonKey.REQUESTED_BY, ctx().flash().get(JsonKey.USER_ID));
    innerMap.put(JsonKey.HEADER, getAllRequestHeaders(request()));
    reqObj.setRequest(innerMap);
    return actorResponseHandler(getActorRef(), reqObj, timeout, null, request());
  } catch (Exception e) {
    return Promise.<Result>pure(createCommonExceptionResponse(e, request()));
  }
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:30,代码来源:CourseBatchController.java

示例10: createPortPairGroup

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
/**
 * Creates a new port pair group.
 *
 * @param stream   port pair group from JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createPortPairGroup(InputStream stream) {

    try {
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode jsonTree = (ObjectNode) mapper.readTree(stream);
        JsonNode port = jsonTree.get("port_pair_group");

        PortPairGroup portPairGroup = codec(PortPairGroup.class).decode((ObjectNode) port, this);
        Boolean issuccess = nullIsNotFound(get(PortPairGroupService.class).createPortPairGroup(portPairGroup),
                                           PORT_PAIR_GROUP_NOT_FOUND);
        return Response.status(OK).entity(issuccess.toString()).build();
    } catch (IOException e) {
        log.error("Exception while creating port pair group {}.", e.toString());
        throw new IllegalArgumentException(e);
    }
}
 
开发者ID:shlee89,项目名称:athena,代码行数:27,代码来源:PortPairGroupWebResource.java

示例11: propertyNamesAreLowerCamelCase

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@Test
public void propertyNamesAreLowerCamelCase() throws Exception {
    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/propertiesAreUpperCamelCase.json", "com.example");
    Class<?> generatedType = resultsClassLoader.loadClass("com.example.UpperCase");

    Object instance = generatedType.newInstance();

    new PropertyDescriptor("property1", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("propertyTwo", generatedType).getWriteMethod().invoke(instance, 2);
    new PropertyDescriptor("propertyThreeWithSpace", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("propertyFour", generatedType).getWriteMethod().invoke(instance, "4");

    JsonNode jsonified = mapper.valueToTree(instance);

    assertNotNull(generatedType.getDeclaredField("property1"));
    assertNotNull(generatedType.getDeclaredField("propertyTwo"));
    assertNotNull(generatedType.getDeclaredField("propertyThreeWithSpace"));
    assertNotNull(generatedType.getDeclaredField("propertyFour"));

    assertThat(jsonified.has("Property1"), is(true));
    assertThat(jsonified.has("PropertyTwo"), is(true));
    assertThat(jsonified.has(" PropertyThreeWithSpace"), is(true));
    assertThat(jsonified.has("propertyFour"), is(true));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:25,代码来源:PropertiesIT.java

示例12: isValid

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
public static boolean isValid(String json, String schema) throws Exception {
    JsonNode schemaNode = JsonLoader.fromString(schema);       
    JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    JsonSchema jsonSchema = factory.getJsonSchema(schemaNode); 
    JsonNode jsonNode = JsonLoader.fromString(json);
    ProcessingReport report = jsonSchema.validate(jsonNode);
    logger.debug("report: {}", report);
    return report.isSuccess();
}
 
开发者ID:intuit,项目名称:karate,代码行数:10,代码来源:SchemaUtils.java

示例13: addEnumConstants

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
private void addEnumConstants(JsonNode node, JDefinedClass _enum, JsonNode customNames, JType type) {
    Collection<String> existingConstantNames = new ArrayList<String>();
    for (int i = 0; i < node.size(); i++) {
        JsonNode value = node.path(i);

        if (!value.isNull()) {
            String constantName = getConstantName(value.asText(), customNames.path(i).asText());
            constantName = makeUnique(constantName, existingConstantNames);
            existingConstantNames.add(constantName);

            JEnumConstant constant = _enum.enumConstant(constantName);
            constant.arg(DefaultRule.getDefaultValue(type, value));
            ruleFactory.getAnnotator().enumConstant(constant, value.asText());
        }
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:17,代码来源:EnumRule.java

示例14: buildSetCustomFieldsUpdateActions_WithDifferentOrderOfCustomFieldValues_ShouldNotBuildUpdateActions

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
@Test
public void buildSetCustomFieldsUpdateActions_WithDifferentOrderOfCustomFieldValues_ShouldNotBuildUpdateActions() {
    final Map<String, JsonNode> oldCustomFields = new HashMap<>();
    oldCustomFields.put("backgroundColor",
        JsonNodeFactory.instance.objectNode().put("de", "rot").put("es", "rojo"));

    final Map<String, JsonNode> newCustomFields = new HashMap<>();
    newCustomFields.put("backgroundColor",
        JsonNodeFactory.instance.objectNode().put("es", "rojo").put("de", "rot"));

    final List<UpdateAction<Category>> setCustomFieldsUpdateActions =
        buildSetCustomFieldsUpdateActions(oldCustomFields, newCustomFields, mock(Category.class),
            CATEGORY_SYNC_OPTIONS);

    assertThat(setCustomFieldsUpdateActions).isNotNull();
    assertThat(setCustomFieldsUpdateActions).isEmpty();
}
 
开发者ID:commercetools,项目名称:commercetools-sync-java,代码行数:18,代码来源:CustomUpdateActionUtilsTest.java

示例15: assertJsonEquals

import com.fasterxml.jackson.databind.JsonNode; //导入依赖的package包/类
public static void assertJsonEquals(String expected, String actual, String... blacklistedFields) {
    LOG.debug("Comparing expected [{}] to actual [{}]", expected, actual);
    DocumentContext expectedDocument = JsonPath.parse(expected);
    DocumentContext actualDocument = JsonPath.parse(actual);

    if (blacklistedFields != null) {
        removeFields(expectedDocument, blacklistedFields);
        removeFields(actualDocument, blacklistedFields);
    }

    try {
        ObjectMapper mapper = new ObjectMapper();

        JsonNode expectedNode = mapper.readTree(expectedDocument.jsonString());
        JsonNode actualNode = mapper.readTree(actualDocument.jsonString());

        assertEquals(expectedNode, actualNode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:Atypon-OpenSource,项目名称:wayf-cloud,代码行数:22,代码来源:HttpTestUtil.java


注:本文中的com.fasterxml.jackson.databind.JsonNode类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。