本文整理匯總了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());
}
示例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"));
}
示例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"));
}
示例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"));
}
示例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());
}
}
示例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());
}
}
示例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;
}
示例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();
}
}
}
示例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;
}
示例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");
}
}
示例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();
}
示例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();
}
示例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();
}
示例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;
}