有什么方法可以将google protobuf消息转换为带有缩进的json吗?

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

我需要使用 C# 将 Google protobuf IMessage 对象保存到 json 文件中。 这是示例代码:

using (var input = File.OpenRead(protodatFile)) 
{
    string jsonString = null;
    message.MergeFrom(input); //read message from protodat file
    JsonFormatter formater = new JsonFormatter(
        new JsonFormatter.Settings(false));
    jsonString = formatter.Format(message);
    System.IO.File.WriteAllText(jsonFile, jsonString);
}

这使用了 Google Protobuf 库中的

JsonFormatter

问题:所有json内容都存储在一行中。当文件很大(> 50 MB)时,很难在文本编辑器中打开/查看。

在这里制作缩进的 jsonFile 的最佳方法是什么?

c# protocol-buffers indentation
3个回答
6
投票

作为一种效率极低的解决方法,可以使用 Json.NET 重新格式化 Protobuffer Json:

// Re-Parse the one-line protobuf json string into an object:
object parsed = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
// Format this object as JSON with indentation:
string jsonWithIndent = Newtonsoft.Json.JsonConvert.SerializeObject(parsed, Newtonsoft.Json.Formatting.Indented);

由于最初的问题询问的是 50MB 文件,对于如此大的文件来说,这可能是一个糟糕的解决方案,但考虑到我在 JsonFormatter.Settings 上找不到任何内容,这就是我想要的。


3
投票

从 Google.Protobuf 版本 3.22.0 开始,您可以使用以下内容:

JsonFormatter formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithIndentation());
output = formatter.Format(msg);

相应问题请参见此处:https://github.com/protocolbuffers/protobuf/pull/9391


0
投票

我尝试使用此代码

JsonFormatter formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithIndentation());
output = formatter.Format(msg);

我收到一个错误: System.InvalidOperationException:“值消息必须包含其中一个的值。”

这个错误的原因是什么?

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