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


Java JSON.parse方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: 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

示例6: create

import com.mongodb.util.JSON; //导入方法依赖的package包/类
@PostMapping
@ApiOperation(value = "Create a device custom data")
@PreAuthorize("hasAuthority('ADD_DEVICE')")
public Object create(
		@PathVariable("application") String applicationId,
		@PathVariable("deviceGuid") String deviceGuid,
        @ApiParam(name = "body", required = true)
		@RequestBody String jsonCustomData) throws BadServiceResponseException, NotFoundResponseException {

    Tenant tenant = user.getTenant();
    Application application = getApplication(applicationId);
    Device device = getDevice(tenant, application, deviceGuid);

    ServiceResponse<DeviceCustomData> deviceResponse = deviceCustomDataService.save(tenant, application, device, jsonCustomData);

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

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

示例7: addUserInDatabase

import com.mongodb.util.JSON; //导入方法依赖的package包/类
/**
 * Adds user into the database.
 *
 * @param newUserData Contains user information like username, and password.
 * @return returns true od false depending on success.
 */
@Override
public synchronized boolean addUserInDatabase (JSONObject newUserData){
    boolean success = true;
    MongoCollection<Document> collection = db.getCollection("userTable");

    JSONObject nameCheck = new JSONObject();
    nameCheck.put("username", newUserData.get("username"));

    BasicDBObject dbObject = (BasicDBObject) JSON.parse(nameCheck.toString());
    Document nameInDB = collection.find(dbObject).first();
    if(nameInDB != null){
        return false;
    }

    Document userInput = Document.parse(newUserData.toString());

    try {
        collection.insertOne(userInput);
    }catch (MongoWriteException e){
        //TODO logg error
        success = false;
    }
    return success;
}
 
开发者ID:kahre,项目名称:Cotton,代码行数:31,代码来源:MongoDBConnector.java

示例8: updateObject

import com.mongodb.util.JSON; //导入方法依赖的package包/类
private String updateObject(String id, String entity) throws ServiceException  {
	MongoDBHelper ds = new MongoDBHelper();
	MongoDatabase db = ds.getConnection();
			
	try {
		MongoCollection<Document> c = db.getCollection(this.collectionName);
		BasicDBObject q = (BasicDBObject) JSON.parse("{\"_id\": {\"$eq\": " + id + "}}");
		Document d = Document.parse(entity);
					
		Document doc = d.get("o", Document.class);
		c.replaceOne(q, doc);
		
		//return object on success, to be consistent with add method
		return doc.toJson();
		
	} catch (Exception ex) {
		ex.printStackTrace();
		
		//wrap and bubble up
		throw ExceptionUtil.getException(Exceptions.ERR_DB, ex.getMessage());
	} finally {
		if (ds !=null) {
			ds.closeConnection();
		}
	}
}
 
开发者ID:Chicago,项目名称:opengrid-svc-template,代码行数:27,代码来源:UpdatableMongoDataProvider.java

示例9: convertToDbObject

import com.mongodb.util.JSON; //导入方法依赖的package包/类
/**
 * Transforms the given jsonString into a list of DBObject instances.
 *
 * @param jsonString    json string
 * @return List of DBObject instances
 */
public static List<DBObject> convertToDbObject(String jsonString)
{
    List<DBObject> dbObjects = new ArrayList<>();
    DBObject dbObject = (DBObject) JSON.parse(jsonString);

    // if it is a list, just add all into the list
    if (dbObject instanceof List)
    {
        for (Object obj: ((List) dbObject))
        {
            dbObjects.add((DBObject) obj);
        }
    }
    else
    {
        dbObjects.add(dbObject);
    }

    return dbObjects;
}
 
开发者ID:genome-nexus,项目名称:genome-nexus,代码行数:27,代码来源:Transformer.java

示例10: before

import com.mongodb.util.JSON; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Before
public void before() throws Exception {

	if (operations.count(new Query(), "books") == 0) {

		File file = new ClassPathResource("books.json").getFile();
		String content = Files.contentOf(file, StandardCharsets.UTF_8);
		List<Object> books = (List<Object>) JSON.parse(content);

		operations.insert(books, "books");
	}
}
 
开发者ID:Just-Fun,项目名称:spring-data-examples,代码行数:14,代码来源:SpringBooksIntegrationTests.java

示例11: convert

import com.mongodb.util.JSON; //导入方法依赖的package包/类
@Override
protected DBObject convert(MongoSession source) {

	try {
		DBObject dbSession = (DBObject) JSON.parse(this.objectMapper.writeValueAsString(source));
		dbSession.put(PRINCIPAL_FIELD_NAME, extractPrincipal(source));
		return dbSession;
	} catch (JsonProcessingException e) {
		throw new IllegalStateException("Cannot convert MongoExpiringSession", e);
	}
}
 
开发者ID:spring-projects,项目名称:spring-session-data-mongodb,代码行数:12,代码来源:JacksonMongoSessionConverter.java

示例12: validate

import com.mongodb.util.JSON; //导入方法依赖的package包/类
@Override
        public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
            String reason = null;
            try {
                Object root = JSON.parse(value);
                if (!(root instanceof BasicDBList)) {
                    reason = "not a valid JsonArray";
                }
            } catch (Exception e) {
//                LOGGER.debug("not a valid JSON list", e);
                reason = "unable to parse JSON";
            }
            return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
        }
 
开发者ID:Asymmetrik,项目名称:nifi-nars,代码行数:15,代码来源:MongoProps.java

示例13: insertImageInDb

import com.mongodb.util.JSON; //导入方法依赖的package包/类
@SuppressWarnings("serial")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response insertImageInDb(String jsonRequest, @Context Request request) throws IOException {
    EndpointUtil.printClientInfo(request);

    DBObject json = ((DBObject) JSON.parse(jsonRequest));
    String imageData = (String) json.get("imageData");
    byte[] screenshotBytes = Base64Utils.decode(imageData);

    String testName = json.get(BaseScreenshotModel.TEST_NAME).toString();
    String testBrowser = json.get(BaseScreenshotModel.TEST_BROWSER).toString();
    String description = json.get(BaseScreenshotModel.DESCRIPTION).toString();

    Type type = new TypeToken<List<Rectangle>>() {
    }.getType();

    String ignoreZonesString = ((Object) json.get(BaseScreenshotModel.IGNORE_ZONES)).toString();
    List<Rectangle> ignoreZones = new ArrayList<>();

    if (ignoreZonesString != null) {
        ignoreZones = GsonUtil.gson.fromJson(ignoreZonesString, type);
    }

    File tmpFile = new File("tmpFile");
    FileUtils.writeByteArrayToFile(tmpFile, screenshotBytes);
    GridFSInputFile gfsFile = GFS_PHOTO.createFile(tmpFile);

    gfsFile.setFilename(String.format("%s|%s|%s", testName, testBrowser, description));
    gfsFile.save();
    // after the file has been saved, get the id and add it into the table of base_images
    BaseScreenshotModel up = new BaseScreenshotModel(testName, testBrowser, description,
        new ObjectId(gfsFile.getId().toString()), ignoreZones);

    TMP_IMAGES.save(up);
    tmpFile.delete();
    return Response.ok().entity(JSON.serialize(up)).build();
}
 
开发者ID:web-innovate,项目名称:selenium-screenshot-watcher,代码行数:39,代码来源:UploadScreenshot.java

示例14: createMatchConfigs

import com.mongodb.util.JSON; //导入方法依赖的package包/类
@PUT
@Path("/{matchName}/{sideName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createMatchConfigs(String document, @PathParam("matchName") String matchName, @PathParam("sideName") String sideName) {

    // Get match config
    MatchConfigDAO matchConfigDAO = new MatchConfigDAO();
    Map<String, Object> searchCriteria = new HashMap();
    searchCriteria.put("_id", matchName);
    List<MatchConfig> matchConfigs = matchConfigDAO.filter(searchCriteria, null, null);
    MatchConfig matchConfig = matchConfigs.get(0);

    //create record
    ARecordDAO aRecordDAO = new ARecordDAO();
    ARecord aRecord = new ARecord();
    aRecord.setMatchName(matchName);
    DBObject dBObject = (DBObject) JSON.parse(document);
    aRecord.setRecordId(UUID.randomUUID().toString());
    aRecord.setdBObject(dBObject);

    //compute key
    List<String> keys = matchConfig.getIdentifingKeys();
    String key = "";
    for (String k : keys) {
        Object value = aRecord.getdBObject().get(k);
        key+= ":"+String.valueOf(value);
    }
    aRecord.setKey(key);
    aRecord.setDisplayId((String) aRecord.getdBObject().get(matchConfig.getDisplayId()));

    aRecordDAO.create(aRecord);

    return Response.ok(aRecord).build();
}
 
开发者ID:nimesh-mittal,项目名称:elastic-match,代码行数:36,代码来源:IndexingResource.java

示例15: document2Pems

import com.mongodb.util.JSON; //导入方法依赖的package包/类
/**
 * 
 * @param tweetDocument
 *            a MongoDB document representing a tweet
 * @param pemsMetaDb
 *            database with the pems data
 * @param pemsMetaCollection
 *            collection with the pems meta data
 * @param pemsdatacollection
 *            collection with the pems station data
 * @return an object containing the pems station data to be mapped to the
 *         tweet
 */
private PemsStationMetaData document2Pems(Document tweetDocument, String pemsMetaDb, String pemsMetaCollection) {

	Assert.notNull(tweetDocument, "The mongodb document representing the tweet to be parsed cannot be null.");
	PemsStationMetaData pems = null;

	Document location = (Document) tweetDocument.get("location");
	Document place = (Document) tweetDocument.get("place");
	if (location != null && !location.isEmpty()) {
		// if available, map gps tag to station
		log.trace("Mapping gps location to PEMS station data.");

		BasicDBObject query = (BasicDBObject) JSON.parse("{location:{$near:{$geometry:" + location.toJson()
				+ ",$minDistance:0,$maxDistance: " + MAX_DIST + "}}}");
		Document metaData = (Document) mongoClient.getDatabase(pemsMetaDb).getCollection(pemsMetaCollection)
				.find(query).first();
		pems = new PemsStationMetaData(metaData);
	} else if (place != null && !place.isEmpty()) {
		// if no gps tag is available, map place to station if available
		log.trace("Mapping place tag to PEMS station data.");
		log.warn("Not yet implemented yet."); // TODO implement place
												// mapping

	} else {
		// no gps tag or place available - do nothing for now
		log.trace("No location or place available for PEMS station data mapping.");
	}

	return pems;
}
 
开发者ID:DiscourseDB,项目名称:discoursedb-core,代码行数:43,代码来源:TwitterConverter.java


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