Java源码示例:org.bson.json.JsonWriterSettings
示例1
@Override
public String getDocumentContent(String ownerType, Long documentId) {
CodeTimer timer = new CodeTimer("Load from documentDb", true);
try {
MongoDatabase mongoDb = getMongoDb();
if (mongoDb != null) {
MongoCollection<Document> mongoCollection = mongoDb.getCollection(getCollectionName(ownerType));
org.bson.Document mongoQuery = new org.bson.Document("document_id", documentId);
org.bson.Document c = mongoCollection.find(mongoQuery).limit(1).projection(fields(include("CONTENT", "isJSON"), excludeId())).first();
if (c == null) {
return null;
} else if (c.getBoolean("isJSON", false)) {
boolean isIndent = PropertyManager.getBooleanProperty(PropertyNames.MDW_MONGODB_FORMAT_JSON , false);
return decodeMongoDoc(c.get("CONTENT", org.bson.Document.class)).toJson(JsonWriterSettings.builder().indent(isIndent).build());
} else {
return c.getString("CONTENT");
}
}
return null;
}
finally {
timer.stopAndLogTiming(null);
}
}
示例2
private String buildBatch(List<Document> documents, String jsonTypeSetting, String prettyPrintSetting) throws IOException {
StringBuilder builder = new StringBuilder();
for (int index = 0; index < documents.size(); index++) {
Document document = documents.get(index);
String asJson;
if (jsonTypeSetting.equals(JSON_TYPE_STANDARD)) {
asJson = getObjectWriter(objectMapper, prettyPrintSetting).writeValueAsString(document);
} else {
asJson = document.toJson(new JsonWriterSettings(true));
}
builder
.append(asJson)
.append( (documents.size() > 1 && index + 1 < documents.size()) ? ", " : "" );
}
return "[" + builder.toString() + "]";
}
示例3
@Test
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
String json = null;
try (MongoClient mongoClient = new MongoClient()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(JsonWriterSettings
.builder()
.outputMode(JsonMode.RELAXED)
.build());
}
String expectedJson = "{\"_id\": \"isbn\", " +
"\"className\": \"com.baeldung.bsontojson.Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";
assertNotNull(json);
assertEquals(expectedJson, json);
}
示例4
@Test
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {
String json = null;
try (MongoClient mongoClient = new MongoClient()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(JsonWriterSettings
.builder()
.dateTimeConverter(new JsonDateTimeConverter())
.build());
}
String expectedJson = "{\"_id\": \"isbn\", " +
"\"className\": \"com.baeldung.bsontojson.Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": \"2020-01-01T17:13:32Z\"}";
assertEquals(expectedJson, json);
}
示例5
private static void assertEquals(List<BsonDocument> actual, List<BsonDocument> expected) {
if (!actual.equals(expected)) {
final JsonWriterSettings settings = JsonWriterSettings.builder().indent(true).build();
// outputs Bson in pretty Json format (with new lines)
// so output is human friendly in IDE diff tool
final Function<List<BsonDocument>, String> prettyFn = bsons -> bsons.stream()
.map(b -> b.toJson(settings)).collect(Collectors.joining("\n"));
// used to pretty print Assertion error
Assertions.assertEquals(
prettyFn.apply(expected),
prettyFn.apply(actual),
"expected and actual Mongo pipelines do not match");
Assertions.fail("Should have failed previously because expected != actual is known to be true");
}
}
示例6
@Test
public void int64Id() {
//9007199254740993
long v = ((long) Math.pow(2, 53)) + 1;
assertNotEquals(v, (double)v);
BsonDocument key = new BsonDocument(ID, new BsonInt64(v));
Object o = gson.fromJson(key.toJson(JsonWriterSettings.builder()
.objectIdConverter((value, writer) -> writer.writeString(value.toHexString()))
.build()), Map.class).get(ID);
assertNotEquals(v, o);
}
示例7
@DoFn.ProcessElement
public void processElement(ProcessContext context) {
context.output(
context
.element()
.toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build()));
}
示例8
@Override
public void writeInto(StringBuilder sink, BsonDocument doc) {
String json = MongoBsonTranslator.translate(doc)
.toJson(new JsonWriterSettings(JsonMode.STRICT));
sink.append(json);
}
示例9
public String writeIntoString(BsonDocument doc) {
return MongoBsonTranslator.translate(doc)
.toJson(new JsonWriterSettings(JsonMode.STRICT));
}
示例10
/**
* Returns a function that checks that a particular MongoDB query
* has been called.
*
* @param expected Expected query (as array)
* @return validation function
*/
private static Consumer<List> mongoChecker(final String... expected) {
return actual -> {
if (expected == null) {
assertThat("null mongo Query", actual, nullValue());
return;
}
if (expected.length == 0) {
CalciteAssert.assertArrayEqual("empty Mongo query", expected,
actual.toArray(new Object[0]));
return;
}
// comparing list of Bsons (expected and actual)
final List<BsonDocument> expectedBsons = Arrays.stream(expected).map(BsonDocument::parse)
.collect(Collectors.toList());
final List<BsonDocument> actualBsons = ((List<?>) actual.get(0))
.stream()
.map(Objects::toString)
.map(BsonDocument::parse)
.collect(Collectors.toList());
// compare Bson (not string) representation
if (!expectedBsons.equals(actualBsons)) {
final JsonWriterSettings settings = JsonWriterSettings.builder().indent(true).build();
// outputs Bson in pretty Json format (with new lines)
// so output is human friendly in IDE diff tool
final Function<List<BsonDocument>, String> prettyFn = bsons -> bsons.stream()
.map(b -> b.toJson(settings)).collect(Collectors.joining("\n"));
// used to pretty print Assertion error
assertEquals(
prettyFn.apply(expectedBsons),
prettyFn.apply(actualBsons),
"expected and actual Mongo queries (pipelines) do not match");
fail("Should have failed previously because expected != actual is known to be true");
}
};
}
示例11
public static void main(String[] args) {
/*
$root": {
"$number": 1,
"$field": {
"$date": "2020-04-08T13:07:27.456Z"
},
"$list": [
{
"$l1": "v1"
},
{
"$l2": "v2"
}
],
"$array": [
1,2
]
},
*/
List<Document> list = Lists.newArrayList();
list.add(new Document("$l1", "v1"));
list.add(new Document("$l2", "v2"));
List<Integer> array = Lists.newArrayList();
array.add(1);
array.add(2);
Document in = new Document("$root",
new Document("$number", -1)
.append("$field", new Date())
.append("$list", list)
.append("$array", array)
);
Document out = ExampleSlowOpsCache.INSTANCE.replaceIllegalChars(in, new Document());
JsonWriterSettings.Builder settingsBuilder = JsonWriterSettings.builder().indent(true);
String json = out.toJson(settingsBuilder.build());
LOG.info(json);
}