當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。