【问题标题】:Is any ways to convert google protobuf message into json with indentation?有什么方法可以将 google protobuf 消息转换为带有缩进的 json?
【发布时间】:2018-12-30 06:00:12
【问题描述】:

我需要使用 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);
}

这使用JsonFormatter from the Google Protobuf library

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

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

【问题讨论】:

  • 这不是链接问题的重复。这个问题是 Google Protobuf 特有的,它有自己的 JSON 序列化逻辑。
  • 愚蠢的这个问题被标记为重复,当它不是。如果您对 Json.Net 依赖项没有问题,请尝试以下操作:stackoverflow.com/a/48153713/459102

标签: c# protocol-buffers indentation


【解决方案1】:

作为一种效率极低的解决方法,可以使用 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 上找不到任何东西,这就是我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多