我正在使用 Google 协议缓冲区,使用 protobuf-csharp-port 库(https://code.google.com/p/protobuf-csharp-port/)。Google.ProtocolBuffers.Serialization 类有一个JsonFormatReader
/JsonFormatWriter
类,当我使用它们时,它们不会将开始和结束的花括号放置到 JSON 文档中,如果我添加开始和结束大括号,它们也无法读取他们编写的相同文档。
所以例如调用
PB.ProtoBufMessage message = CreateMyMessage();
string json;
using (StringWriter sw = new StringWriter())
{
ICodedOutputStream output = JsonFormatWriter.CreateInstance(sw);
message.WriteTo(output);
output.Flush();
json = sw.ToString();
}
创建:
"\"field1\":\"prop1\",\"field2\":1,\"subitem\":{\"x\":0,\"y\":0,\"z\":0}"
如果我尝试解析
String jsonmessage = "{\"field1\":\"prop1\",\"field2\":1,\"subitem\":{\"x\":0,\"y\":0,\"z\":0}}"
使用
PB.ProtoBufMessage copy;
ICodedInputStream input = JsonFormatReader.CreateInstance(jsonmessage);
copy = PB.ProtoBufMessage.CreateBuilder().MergeFrom(input).Build();
我得到以下信息:
(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 ...
为什么缺少 { },这是有效的 JSON 吗?