I am working on using Google Protocol Buffers, using the protobuf-csharp-port library (https://code.google.com/p/protobuf-csharp-port/).
The Google.ProtocolBuffers.Serialization class has a JsonFormatReader
/ JsonFormatWriter
class, when I use them they do not place beginning and ending curly braces to the JSON document, nor they can read the same document they write if I add beginning and ending braces.
So for example Calling
PB.ProtoBufMessage message = CreateMyMessage();
string json;
using (StringWriter sw = new StringWriter())
{
ICodedOutputStream output = JsonFormatWriter.CreateInstance(sw);
message.WriteTo(output);
output.Flush();
json = sw.ToString();
}
Creates:
"\"field1\":\"prop1\",\"field2\":1,\"subitem\":{\"x\":0,\"y\":0,\"z\":0}"
If I try to parse
String jsonmessage = "{\"field1\":\"prop1\",\"field2\":1,\"subitem\":{\"x\":0,\"y\":0,\"z\":0}}"
using
PB.ProtoBufMessage copy;
ICodedInputStream input = JsonFormatReader.CreateInstance(jsonmessage);
copy = PB.ProtoBufMessage.CreateBuilder().MergeFrom(input).Build();
I get the following:
(1:1) error: Unexpected token '{', expected: '"'.
at Google.ProtocolBuffers.Serialization.JsonCursor.Assert(Boolean cond, Char expected)
at Google.ProtocolBuffers.Serialization.JsonCursor.Consume(Char ch)
at Google.ProtocolBuffers.Serialization.JsonCursor.ReadString()
at Google.ProtocolBuffers.Serialization.JsonFormatReader.PeekNext(String& field)
at Google.ProtocolBuffers.Serialization.AbstractReader.Google.ProtocolBuffers.ICodedInputStream.ReadTag(UInt32& fieldTag, String& fieldName)
at ...
Why is the { } missing, and is this valid JSON?
You need to write/read message start/end. Like:
output.WriteMessageStart();
message.WriteTo(output);
output.WriteMessageEnd();
Similary wilhe reading:
input.ReadMessageStart();
builder.MergeFrom(input);
input.ReadMessageEnd();
The above code works with json and binary reader/writers.