본문 바로가기
Programming/C#

[C#] BsonDocument를 JSON으로 변환하기

by 째스터 2024. 2. 9.
728x90

MongoDB를 사용하면 BsonDocument와 친해지게 된다.
서버와 클라이언트의 통신에는 JSON 형태로 하는 경우가 많아서 JSON으로 변환이 필요한 상황이 있다.

ToJson() BsonExtensionMethods를 이용하면 JSON string으로 변환할 수 있다.

var actual = collection.Find(c => c.Id == targetId).FirstOrDefault();
var json = actual.ToJson();

그런데 다음과 같이 ObjectId(), NumberDecimal(), IsoDate() 같은 값들이 표시된다.
그리고 이것은 JSON parsing error를 발생시킬 수 있다.

{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "event": "Data Processing",
  "date": ISODate("2023-01-01T00:00:00Z"),
  "participants": 100
}

다음과 같은 JsonOutputMode.RelaxedExtendedJson 설정으로 이를 방지할 수 있다.

var actual = collection.Find(c => c.Id == targetId).FirstOrDefault();
var json = actual.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.RelaxedExtendedJson });
{
  "_id": {"$oid": "507f1f77bcf86cd799439011"},
  "event": {"$string": "Data Processing"},
  "date": {"$date": {"$numberLong": "1672444800000"}},
  "participants": {"$numberInt": "100"}
}

https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Bson/IO/JsonOutputMode.cs

 

728x90

댓글