Skip to content

Commit

Permalink
feat: JsonNode support (#528)
Browse files Browse the repository at this point in the history
  • Loading branch information
joesdu authored Sep 14, 2024
2 parents eb43754 + a991c6d commit f35b465
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
37 changes: 37 additions & 0 deletions src/EasilyNET.MongoSerializer.AspNetCore/JsonNodeSerializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Bson.Serialization;
using System.Text.Json.Nodes;

namespace EasilyNET.MongoSerializer.AspNetCore;

/// <summary>
/// JsonNode Support
/// </summary>
public class JsonNodeSerializer : SerializerBase<JsonNode>
{
const string EmptyObject = "{}";

/// <summary>
/// if null write {}
/// </summary>
/// <param name="context"></param>
/// <param name="args"></param>
/// <param name="value"></param>
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, JsonNode value)
{
var json = value?.ToString() ?? EmptyObject;
context?.Writer?.WriteString(json);
}

/// <summary>
/// if null return {}
/// </summary>
/// <param name="context"></param>
/// <param name="args"></param>
/// <returns></returns>
public override JsonNode Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
string json = context?.Reader?.ReadString() ?? EmptyObject;
return JsonNode.Parse(json)!;
}
}
9 changes: 8 additions & 1 deletion src/EasilyNET.MongoSerializer.AspNetCore/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ EasilyNET.Mongo.AspNetCore 扩展,用于支持一些非默认类型的序列化
2. 转换成 Ticks 的方式存储
3. 若想转化成其他类型也可自行实现,如:转化成 ulong 类型
- 添加动态类型支持[object 和 dynamic], 2.20 版后官方又加上了.
- 添加.Net6 Date/Time Only 类型支持(TimeOnly 理论上应该是兼容原 TimeSpan 数据类型).
JsonArray.
- 添加JsonNode类型支持.

---

- 配合 EasilyNET.Mongo.AspNetCore 或单独使用

- JsonNode类型因为反序列化时不支持Unicode字符,如果需要序列化插入至其他地方(例如Redis),在序列化时需要将JsonSerializerOptions的Encoder属性设置为System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping.


```csharp
builder.Services.AddMongoContext<DbContext>(builder.Configuration)
// 添加自定义序列化
Expand All @@ -24,4 +28,7 @@ builder.Services.RegisterSerializer(new TimeOnlySerializerAsString());
// 或者将他们存储为long类型的Ticks,也可以自己组合使用.
builder.Services.RegisterSerializer(new DateOnlySerializerAsTicks());
builder.Services.RegisterSerializer(new TimeOnlySerializerAsTicks());

// 添加JsonNode支持
builder.Services.RegisterSerializer(new JsonNodeSerializer());
```

0 comments on commit f35b465

Please sign in to comment.