10

I need to save Google protobuf IMessage object into json file, using C#. here is sample code:

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);
}

This uses the JsonFormatter from the Google Protobuf library.

The problem: all json content is stored in one line. when file is quite big(>50 MB) it is hard to open/view in text editor.

What is the best way to make indented jsonFile here?

Martin Ba
  • 37,187
  • 33
  • 183
  • 337
Dorrian Do
  • 101
  • 1
  • 1
  • 3
  • 4
    This is NOT a dupicate of the linked question. This question is specific to Google Protobuf, which has its own JSON serialization logic. – Antoine Aubry Mar 20 '19 at 17:36
  • Silly this question is marked as a duplicate, when it is not. If you are OK with a Json.Net dependency, try something like this: https://stackoverflow.com/a/48153713/459102 – Aaron Hudon Jul 24 '19 at 19:15

2 Answers2

6

As an extremely inefficient workaround, one can use Json.NET to re-format the 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);

Since the original question asked about a 50MB file, this is probably a bad solution for such large-ish files, but given that I couldn't find anything on JsonFormatter.Settings, it was what I reached for.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337
3

As of version 3.22.0 of Google.Protobuf you can use the following:

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

See here for the corresponding issue: https://github.com/protocolbuffers/protobuf/pull/9391

Fabian
  • 308
  • 2
  • 11