BAEL-3943 Bson to json (#9079)

This commit is contained in:
Benjamin Caure 2020-04-14 07:08:04 +02:00 committed by GitHub
parent 62bf6e13f9
commit bc872d3742
4 changed files with 243 additions and 18 deletions

View File

@ -10,3 +10,4 @@ This module contains articles about MongoDB in Java.
- [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support)
- [Introduction to Morphia Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia)
- [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations)
- [MongoDB BSON to JSON](https://www.baeldung.com/bson-to-json)

View File

@ -1,5 +1,7 @@
package com.baeldung.morphia.domain;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@ -29,28 +31,13 @@ public class Book {
private double cost;
@Reference
private Set<Book> companionBooks;
@Property
private LocalDateTime publishDate;
public Book() {
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getCost() {
return cost;
}
public void addCompanionBooks(Book book) {
if (companionBooks != null)
this.companionBooks.add(book);
}
public Book(String isbn, String title, String author, double cost, Publisher publisher) {
this.isbn = isbn;
this.title = title;
@ -60,6 +47,71 @@ public class Book {
this.companionBooks = new HashSet<>();
}
// Getters and setters ...
public String getIsbn() {
return isbn;
}
public Book setIsbn(String isbn) {
this.isbn = isbn;
return this;
}
public String getTitle() {
return title;
}
public Book setTitle(String title) {
this.title = title;
return this;
}
public String getAuthor() {
return author;
}
public Book setAuthor(String author) {
this.author = author;
return this;
}
public Publisher getPublisher() {
return publisher;
}
public Book setPublisher(Publisher publisher) {
this.publisher = publisher;
return this;
}
public double getCost() {
return cost;
}
public Book setCost(double cost) {
this.cost = cost;
return this;
}
public LocalDateTime getPublishDate() {
return publishDate;
}
public Book setPublishDate(LocalDateTime publishDate) {
this.publishDate = publishDate;
return this;
}
public Set<Book> getCompanionBooks() {
return companionBooks;
}
public Book addCompanionBooks(Book book) {
if (companionBooks != null)
this.companionBooks.add(book);
return this;
}
@Override
public String toString() {
return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]";
@ -113,4 +165,4 @@ public class Book {
return true;
}
}
}

View File

@ -0,0 +1,142 @@
package com.baeldung.bsontojson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bson.Document;
import org.bson.json.Converter;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
import org.bson.json.StrictJsonWriter;
import org.bson.types.ObjectId;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.morphia.domain.Book;
import com.baeldung.morphia.domain.Publisher;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
public class BsonToJsonIntegrationTest {
private static final String DB_NAME = "library";
private static Datastore datastore;
@BeforeClass
public static void setUp() {
Morphia morphia = new Morphia();
morphia.mapPackage("com.baeldung.morphia");
datastore = morphia.createDatastore(new MongoClient(), DB_NAME);
datastore.ensureIndexes();
datastore.save(new Book()
.setIsbn("isbn")
.setTitle("title")
.setAuthor("author")
.setCost(3.95)
.setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher"))
.setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME))
.addCompanionBooks(new Book().setIsbn("isbn2")));
}
@AfterClass
public static void tearDown() {
datastore.delete(datastore.createQuery(Book.class));
}
@Test
public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() {
String json = null;
try (MongoClient mongoClient = new MongoClient()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson();
}
String expectedJson = "{\"_id\": \"isbn\", " +
"\"className\": \"com.baeldung.morphia.domain.Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": {\"$date\": 1577898812000}}";
assertNotNull(json);
assertEquals(expectedJson, json);
}
@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.morphia.domain.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);
}
@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.morphia.domain.Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
"\"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": \"2020-01-01T17:13:32Z\"}";
assertEquals(expectedJson, json);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.bsontojson;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.TimeZone;
import org.bson.json.Converter;
import org.bson.json.StrictJsonWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonDateTimeConverter implements Converter<Long> {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class);
static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT
.withZone(ZoneId.of("UTC"));
@Override
public void convert(Long value, StrictJsonWriter writer) {
try {
Instant instant = new Date(value).toInstant();
String s = DATE_TIME_FORMATTER.format(instant);
writer.writeString(s);
} catch (Exception e) {
LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e);
}
}
}