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


Java JSON类代码示例

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


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

示例1: getGardenLocationsAsJson

import com.mongodb.util.JSON; //导入依赖的package包/类
/**
 * Takes `uploadID` and returns all bed names as a json format string
 * @param uploadID - the year that the data was uploaded
 * @return String representation of json with all bed names
 */
public String getGardenLocationsAsJson(String uploadID){
    AggregateIterable<Document> documents
            = plantCollection.aggregate(
            Arrays.asList(
                    Aggregates.match(eq("uploadID", uploadID)), //!! Order is important here
                    Aggregates.group("$gardenLocation"),
                    Aggregates.sort(Sorts.ascending("_id"))
            ));

    List<Document> listDoc = new ArrayList<>();
    for (Document doc : documents) {
        listDoc.add(doc);
    }
    listDoc.sort(new BedComparator());

    return JSON.serialize(listDoc);
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-dorfner-v2,代码行数:23,代码来源:PlantController.java

示例2: incrementMetadata

import com.mongodb.util.JSON; //导入依赖的package包/类
@Test
public void incrementMetadata() {
//This method is called from inside of getPlantByPlantId();
    boolean myPlant = plantController.
            incrementMetadata("58d1c36efb0cac4e15afd278", "pageViews");
    assertFalse(myPlant);
    boolean myPlant2 = plantController.incrementMetadata("16001.0","pageViews");
    assertTrue(myPlant2);


//This is necessary to test the data separately from getPlantByPlantId();
    Document searchDocument = new Document();
    searchDocument.append("id", "16001.0");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plantCollection = db.getCollection("plants");
    String before = JSON.serialize(plantCollection.find(searchDocument));
    plantController.incrementMetadata("16001.0","pageViews");
    String after = JSON.serialize(plantCollection.find(searchDocument));

    assertFalse(before.equals(after));
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-3-sixguysburgers-fries,代码行数:23,代码来源:UnorganizedTests.java

示例3: getDataFromDatabase

import com.mongodb.util.JSON; //导入依赖的package包/类
/**
 * Returns data from the database.
 *
 * @param searchKeys JSONObject containing the information regarding what data the return needs to contain.
 * @return  returns an JSONObject containing desired data.
 */
@Override
public synchronized JSONObject getDataFromDatabase (JSONObject searchKeys){
    JSONArray retArray = new JSONArray();
    JSONObject returnValue = new JSONObject();

    BasicDBObject dbObject = (BasicDBObject) JSON.parse(searchKeys.toString());

    FindIterable<Document> request = db.getCollection("requestTable").find(dbObject);
    for(Document d: request){
        retArray.put(new JSONObject(d.toJson()));
    }

    returnValue.put("dataArray", retArray);
    return returnValue;
}
 
开发者ID:kahre,项目名称:Cotton,代码行数:22,代码来源:MongoDBConnector.java

示例4: testGetZipsWithLimit

import com.mongodb.util.JSON; //导入依赖的package包/类
@Test
public void testGetZipsWithLimit() throws Exception {
	StringWriter sw = new StringWriter();
	PrintWriter pw = new PrintWriter(sw);

	when(response.getWriter()).thenReturn(pw);
	when(request.getPathInfo()).thenReturn("/zips");
	int limit = 50;
	@SuppressWarnings("serial")
	HashMap<String, String[]> parameterMap = new HashMap<String, String[]>() {
		{
			put("limit", new String[] { "50" });
		}
	};
	when(request.getParameterMap()).thenReturn(parameterMap);

	new MongoCrudServlet().doGet(request, response);

	String result = sw.getBuffer().toString().trim();
	System.out.println("Json Result As String is : " + result.length() + " characters long");
	assertTrue("somehow got a very small JSON resposne: " + result, result.length() > 20);
	System.out.println("first few lines of Json Result:\n" + result.substring(0, 400));

	BasicDBList json = (BasicDBList) JSON.parse(result);
	assertTrue("json.size() should be " + limit + ", got " + json.size() + " instead", limit == json.size());
}
 
开发者ID:timbaileyjones,项目名称:nomopojo,代码行数:27,代码来源:MongoCrudServletTest.java

示例5: testMaps

import com.mongodb.util.JSON; //导入依赖的package包/类
@Test
public void testMaps() throws Exception {
  Schema schema = Maps.SCHEMA$;

  GenericRecordBuilder builder = new GenericRecordBuilder(schema);
  builder.set("maps", ImmutableMap.of("key1", ImmutableMap.of("value1", 1, "value2", 2), "key2",
      ImmutableMap.of(), "key3", ImmutableMap.of("value3", 3)));
  Record record1 = builder.build();

  String json = "{\"maps\": {\"key1\": {\"value1\": 1, \"value2\": 2}, \"key2\": {}, \"key3\": {\"value3\": 3}}}";
  DBObject object = (DBObject) JSON.parse(json);
  Record record2 = RecordConverter.toRecord(schema, object, getClass().getClassLoader());

  // Convert into JsonNode before comparison, so the maps equal even if keys are reordered.
  assertThat(JSON.parse(AvroHelper.toSimpleJson(schema, record2)), is(JSON.parse(AvroHelper.toSimpleJson(schema, record1))));
}
 
开发者ID:tfeng,项目名称:toolbox,代码行数:17,代码来源:TestDocumentDecoder.java

示例6: listPlants

import com.mongodb.util.JSON; //导入依赖的package包/类
/**
 * List all plants within the database, filtered by uploadId, gardenLocation and commonName
 * @param queryParams
 * @param uploadId
 * @return
 */
public String listPlants(Map<String, String[]> queryParams, String uploadId) {

    if (!ExcelParser.isValidUploadId(db, uploadId))
        return "null";

    //Create a filter based on query params
    Document filterDoc = new Document();
    filterDoc.append("uploadId", uploadId);

    if (queryParams.containsKey("gardenLocation")) {
        String location =(queryParams.get("gardenLocation")[0]);
        filterDoc = filterDoc.append("gardenLocation", location);
    }


    if (queryParams.containsKey("commonName")) {
        String commonName =(queryParams.get("commonName")[0]);
        filterDoc = filterDoc.append("commonName", commonName);
    }

    FindIterable<Document> matchingPlants = plantCollection.find(filterDoc);
    matchingPlants.sort(Sorts.ascending("commonName", "cultivar"));

    return JSON.serialize(matchingPlants);
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-revolverenguardia-1,代码行数:32,代码来源:PlantController.java

示例7: listPlants

import com.mongodb.util.JSON; //导入依赖的package包/类
public String listPlants(Map<String, String[]> queryParams, String uploadId) {
    Document filterDoc = new Document();
    filterDoc.append("uploadId", uploadId);

    if (queryParams.containsKey("gardenLocation")) {
        String location = (queryParams.get("gardenLocation")[0]);
        filterDoc = filterDoc.append("gardenLocation", location);
    }


    if (queryParams.containsKey("commonName")) {
        String commonName = (queryParams.get("commonName")[0]);
        filterDoc = filterDoc.append("commonName", commonName);
    }

    FindIterable<Document> matchingPlants = plantCollection.find(filterDoc);


    return JSON.serialize(matchingPlants);
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-3-sixguysburgers-fries,代码行数:21,代码来源:PlantController.java

示例8: listPlants

import com.mongodb.util.JSON; //导入依赖的package包/类
public String listPlants(Map<String, String[]> queryParams, String uploadID) {
    Document filterDoc = new Document();
    filterDoc.append("uploadID", uploadID);

    if (queryParams.containsKey("gardenLocation")) {
        String location =(queryParams.get("gardenLocation")[0]);
        filterDoc = filterDoc.append("gardenLocation", location);
    }


    if (queryParams.containsKey("commonName")) {
        String commonName =(queryParams.get("commonName")[0]);
        filterDoc = filterDoc.append("commonName", commonName);
    }

    FindIterable<Document> matchingPlants = plantCollection.find(filterDoc);
    List<Document> sortedPlants = new ArrayList<>();
    for (Document doc : matchingPlants) {
        sortedPlants.add(doc);
    }
    sortedPlants.sort(new PlantComparator());
    return JSON.serialize(sortedPlants);
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-4-dorfner-v2,代码行数:24,代码来源:PlantController.java

示例9: listFlowers

import com.mongodb.util.JSON; //导入依赖的package包/类
public String listFlowers(Map<String, String[]> queryParams) {
    Document filterDoc = new Document();

    if (queryParams.containsKey("cultivar")) {
        String targetCultivar = queryParams.get("cultivar")[0];
        filterDoc = filterDoc.append("cultivar", targetCultivar);
    }

    if (queryParams.containsKey("source")) {
        String targetSource = queryParams.get("source")[0];
        filterDoc = filterDoc.append("source", targetSource);
    }

    if (queryParams.containsKey("gardenLocation")) {
        String targetLocation = queryParams.get("gardenLocation")[0];
        filterDoc = filterDoc.append("gardenLocation", targetLocation);
    }

    if (queryParams.containsKey("year")) {
        int targetYear = Integer.parseInt(queryParams.get("year")[0]);
        filterDoc = filterDoc.append("year", targetYear);
    }

    FindIterable<Document> matchingFlowers = flowerCollection.find(filterDoc);

    return JSON.serialize(matchingFlowers);
}
 
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-2-spraguesanborn,代码行数:28,代码来源:FlowerController.java

示例10: insert_refined_payload_test

import com.mongodb.util.JSON; //导入依赖的package包/类
@Test
public void insert_refined_payload_test() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new StoreInMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify Wrapped Payload
    MockFlowFile out = runner.getFlowFilesForRelationship(AbstractMongoProcessor.REL_SUCCESS).get(0);
    BasicDBObject actual = (BasicDBObject) JSON.parse(new String(out.toByteArray(), StandardCharsets.UTF_8));
    assertNotNull(actual.getString("d"));
}
 
开发者ID:Asymmetrik,项目名称:nifi-nars,代码行数:21,代码来源:StoreInMongoIT.java

示例11: insert_test

import com.mongodb.util.JSON; //导入依赖的package包/类
@Test
public void insert_test() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new StoreInMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");

    runner.enqueue("{\"a\":\"a\"}".getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify Wrapped Payload
    MockFlowFile out = runner.getFlowFilesForRelationship(AbstractMongoProcessor.REL_SUCCESS).get(0);
    BasicDBObject actual = (BasicDBObject) JSON.parse(new String(out.toByteArray(), StandardCharsets.UTF_8));
    assertEquals("a", actual.getString("a"));
}
 
开发者ID:Asymmetrik,项目名称:nifi-nars,代码行数:19,代码来源:StoreInMongoIT.java

示例12: testQuery

import com.mongodb.util.JSON; //导入依赖的package包/类
@Test
public void testQuery() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new QueryMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");
    runner.setProperty(MongoProps.QUERY, "{\"criteria\": \"${test_attribute}\"}");

    ProcessSession session = runner.getProcessSessionFactory().createSession();
    FlowFile ff = session.create();
    ff = session.putAttribute(ff, "test_attribute", "12345");

    runner.enqueue(ff);
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    MockFlowFile out = runner.getFlowFilesForRelationship(AbstractMongoProcessor.REL_SUCCESS).get(0);
    BasicDBObject actual = (BasicDBObject) JSON.parse(new String(out.toByteArray(), StandardCharsets.UTF_8));
    assertEquals("[ \"12345\" , \"23456\" , \"34567\"]", actual.getString("criteria"));
}
 
开发者ID:Asymmetrik,项目名称:nifi-nars,代码行数:23,代码来源:QueryMongoIT.java

示例13: serialize

import com.mongodb.util.JSON; //导入依赖的package包/类
@Override
public JsonElement serialize(Module module, Type type, JsonSerializationContext jsonSerializationContext) {
  JsonObject object = new JsonObject();
  JsonParser parser = new JsonParser();

  object.add(FIELD_CLASS, new JsonPrimitive(module.getClazz()));
  object.add(FIELD_ABSTRACTION_ID, new JsonPrimitive(module.getAbstractionId()));
  object.add(FIELD_PARALLELISM, new JsonPrimitive(module.getParallelism()));

  if (module.getParams().size() > 0) {
    object.add(FIELD_PARAMS, parser.parse(JSON.serialize(module.getParams())).getAsJsonObject());
  }

  if (module.getSources().size() > 0) {
    object.add(FIELD_SOURCES, parser.parse(JSON.serialize(module.getSources())).getAsJsonObject());
  }

  return object;
}
 
开发者ID:telefonicaid,项目名称:fiware-sinfonier,代码行数:20,代码来源:ModuleSerializer.java

示例14: read

import com.mongodb.util.JSON; //导入依赖的package包/类
@GetMapping(path = "/{deviceModelName}/{locationName}")
@ApiOperation(
        value = "Get a device config by guid",
        response = RestResponse.class
)
@PreAuthorize("hasAuthority('SHOW_DEVICE_CONFIG')")
public Object read(
        @PathVariable("application") String applicationId,
        @PathVariable("deviceModelName") String deviceModelName,
        @PathVariable("locationName") String locationName) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);
    DeviceModel deviceModel = getDeviceModel(tenant, application, deviceModelName);
    Location location = getLocation(tenant, application, locationName);

    ServiceResponse<String> restDestinationResponse = deviceConfigSetupService.findByModelAndLocation(tenant, application, deviceModel, location);

    if (!restDestinationResponse.isOk()) {
        throw new NotFoundResponseException(restDestinationResponse);
    } else {
        return JSON.parse(restDestinationResponse.getResult());
    }

}
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:26,代码来源:DeviceConfigRestController.java

示例15: read

import com.mongodb.util.JSON; //导入依赖的package包/类
@GetMapping
@ApiOperation(
        value = "Get a application document by collection and key",
        response = RestResponse.class
)
@PreAuthorize("hasAuthority('SHOW_APPLICATION')")
public Object read(
		@PathVariable("application") String applicationId,
		@PathVariable("collection") String collection,
		@PathVariable("key") String key) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);

    ServiceResponse<ApplicationDocumentStore> deviceResponse = applicationDocumentStoreService.findUniqueByTenantApplication(tenant, application, collection, key);

    if (!deviceResponse.isOk()) {
        throw new NotFoundResponseException(deviceResponse);
    } else {
        return JSON.parse(deviceResponse.getResult().getJson());
    }

}
 
开发者ID:KonkerLabs,项目名称:konker-platform,代码行数:24,代码来源:ApplicationDocumentStoreRestController.java


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