我应该使用字符串还是值作为序列化对象消息中的类型吗?

问题描述 投票:0回答:1

目标
我想在 gRPC 消息中保存序列化为 JSON 的对象。

信息
Microsoft 文档表示对 JSON 使用类型

google.protobuf.Value

然后应使用
Value.Parser.ParseJson
转换序列化对象。
并在另一侧再次使用
JsonFormatter.Default.Format
进行转换,以便可以反序列化。
https://learn.microsoft.com/en-us/aspnet/core/grpc/protobuf?view=aspnetcore-8.0#value

问题
没有解释原因。 如果我使用

string
作为类型,我不必使用
Value.Parser.ParseJson
进行转换。

问题
如果我使用

string
可以吗?还是
google.protobuf.Value
有我看不到的优势?
(无论使用
string
还是
google.protobuf.Value
,您都可以看到输出的差异。)

gRPC 消息

message PingResponseMessage {
  google.protobuf.Timestamp ResponseTimeUtc = 1;
  string JsonString = 2;
  google.protobuf.Value JsonValue = 3;
}

创建 gRPC 消息

Settings settings = new() {Name = "Dog", Port = 4000};
PingResponseMessage pingResponseMessage = new()
{
    ResponseTimeUtc = Timestamp.FromDateTime(DateTime.UtcNow),
    JsonString      = JsonConvert.SerializeObject(settings),
    JsonValue       = Value.Parser.ParseJson(JsonConvert.SerializeObject(settings)),
};

输出

{
    "ResponseTimeUtc": {
        "seconds": "1711525732",
        "nanos": 394125400
    },
    "JsonString": "{\"Name\":\"Dog\",\"Port\":4000}",
    "JsonValue": {
        "struct_value": {
            "fields": {
                "Name": {
                    "string_value": "Dog"
                },
                "Port": {
                    "number_value": 4000
                }
            }
        }
    }
}
c# json grpc grpc-c#
1个回答
0
投票

如果我使用字符串可以吗?还是 google.protobuf.Value 有我看不到的优势?

使用

Value
的优点是任何使用另一端结构的人都不必自己解析 JSON,或者担心特定 JSON 格式化程序的奇怪之处(例如无穷大的表示等)。

如果另一方实际上想要它作为 JSON(例如使用 Json.NET 或 System.Text.Json 反序列化为不同的表示形式),那么通过 Value

有点
效率低下。另一方面,另一方可能很乐意将其处理为“通常表示为 JSON 的相同结构”(这基本上就是
Value
),在这种情况下,他们可以直接这样做,而无需任何额外的字符串解析。 (并且不用担心非标准 JSON。)

© www.soinside.com 2019 - 2024. All rights reserved.