瀏覽代碼

Added convenience methods for to/from xml and json

csharptest 14 年之前
父節點
當前提交
f292523df9

+ 1 - 1
src/ProtoBench/Program.cs

@@ -158,7 +158,7 @@ namespace Google.ProtocolBuffers.ProtoBench
                 } );
                 RunBenchmark("Serialize to json", jsonBytes.Length, () => 
                 {
-                    JsonFormatWriter.CreateInstance(new MemoryStream()).WriteMessage(sampleMessage); 
+                    JsonFormatWriter.CreateInstance().WriteMessage(sampleMessage); 
                 });
                 RunBenchmark("Serialize to json via xml", jsonBytes.Length,
                     () =>

+ 3 - 3
src/ProtocolBuffers.Test/CompatTests/CompatibilityTests.cs

@@ -73,7 +73,7 @@ namespace Google.ProtocolBuffers.CompatTests
 
         #region Test message builders
 
-        private static TestAllTypes.Builder AddAllTypes(TestAllTypes.Builder builder)
+        protected static TestAllTypes.Builder AddAllTypes(TestAllTypes.Builder builder)
         {
             return builder.SetOptionalInt32(1001)
                 .SetOptionalInt64(1001)
@@ -96,7 +96,7 @@ namespace Google.ProtocolBuffers.CompatTests
             ;
         }
 
-        private static TestAllTypes.Builder AddRepeatedTypes(TestAllTypes.Builder builder, int size)
+        protected static TestAllTypes.Builder AddRepeatedTypes(TestAllTypes.Builder builder, int size)
         {
             //repeated values
             for (int i = 0; i < size; i++)
@@ -122,7 +122,7 @@ namespace Google.ProtocolBuffers.CompatTests
             return builder;
         }
 
-        private static TestPackedTypes.Builder AddPackedTypes(TestPackedTypes.Builder builder, int size)
+        protected static TestPackedTypes.Builder AddPackedTypes(TestPackedTypes.Builder builder, int size)
         {
             for(int i=0; i < size; i++ )
                 builder.AddPackedInt32(1001)

+ 1 - 0
src/ProtocolBuffers.Test/CompatTests/XmlCompatibilityTests.cs

@@ -1,5 +1,6 @@
 using System.IO;
 using Google.ProtocolBuffers.Serialization;
+using Google.ProtocolBuffers.TestProtos;
 using NUnit.Framework;
 
 namespace Google.ProtocolBuffers.CompatTests

+ 22 - 0
src/ProtocolBuffers.Test/TestWriterFormatJson.cs

@@ -31,6 +31,28 @@ namespace Google.ProtocolBuffers
                 Assert.IsTrue(Content.IndexOf(expect) >= 0, "Expected to find content '{0}' in: \r\n{1}", expect, Content);
         }
 
+        [Test]
+        public void TestToJsonParseFromJson()
+        {
+            TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
+            string json = msg.ToJson();
+            Assert.AreEqual("{\"default_bool\":true}", json);
+            TestAllTypes copy = TestAllTypes.ParseFromJson(json);
+            Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
+            Assert.AreEqual(msg, copy);
+        }
+
+        [Test]
+        public void TestToJsonParseFromJsonReader()
+        {
+            TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
+            string json = msg.ToJson();
+            Assert.AreEqual("{\"default_bool\":true}", json);
+            TestAllTypes copy = TestAllTypes.ParseFromJson(new StringReader(json));
+            Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
+            Assert.AreEqual(msg, copy);
+        }
+
         [Test]
         public void TestJsonFormatted()
         {

+ 22 - 0
src/ProtocolBuffers.Test/TestWriterFormatXml.cs

@@ -12,6 +12,28 @@ namespace Google.ProtocolBuffers
     [TestFixture]
     public class TestWriterFormatXml
     {
+        [Test]
+        public void TestToXmlParseFromXml()
+        {
+            TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
+            string xml = msg.ToXml();
+            Assert.AreEqual("<root><default_bool>true</default_bool></root>", xml);
+            TestAllTypes copy = TestAllTypes.ParseFromXml(XmlReader.Create(new StringReader(xml)));
+            Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
+            Assert.AreEqual(msg, copy);
+        }
+
+        [Test]
+        public void TestToXmlParseFromXmlWithRootName()
+        {
+            TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
+            string xml = msg.ToXml("message");
+            Assert.AreEqual("<message><default_bool>true</default_bool></message>", xml);
+            TestAllTypes copy = TestAllTypes.ParseFromXml("message", XmlReader.Create(new StringReader(xml)));
+            Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
+            Assert.AreEqual(msg, copy);
+        }
+
         [Test]
         public void TestEmptyMessage()
         {

+ 21 - 0
src/ProtocolBuffers/AbstractMessage.cs

@@ -121,6 +121,27 @@ namespace Google.ProtocolBuffers
             return TextFormat.PrintToString(this);
         }
 
+        public string ToJson()
+        {
+            Serialization.JsonFormatWriter w = Serialization.JsonFormatWriter.CreateInstance();
+            w.WriteMessage(this);
+            return w.ToString();
+        }
+
+        public string ToXml()
+        {
+            StringWriter w = new StringWriter(new System.Text.StringBuilder(4096));
+            Serialization.XmlFormatWriter.CreateInstance(w).WriteMessage(this);
+            return w.ToString();
+        }
+
+        public string ToXml(string rootElementName)
+        {
+            StringWriter w = new StringWriter(new System.Text.StringBuilder(4096));
+            Serialization.XmlFormatWriter.CreateInstance(w).WriteMessage(rootElementName, this);
+            return w.ToString();
+        }
+
         public override sealed void PrintTo(TextWriter writer)
         {
             TextFormat.Print(this, writer);

+ 1 - 1
src/ProtocolBuffers/ExtendableBuilder.cs

@@ -42,7 +42,7 @@ namespace Google.ProtocolBuffers
 {
     public abstract class ExtendableBuilder<TMessage, TBuilder> : GeneratedBuilder<TMessage, TBuilder>
         where TMessage : ExtendableMessage<TMessage, TBuilder>
-        where TBuilder : GeneratedBuilder<TMessage, TBuilder>
+        where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
     {
         protected ExtendableBuilder()
         {

+ 1 - 1
src/ProtocolBuffers/ExtendableMessage.cs

@@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers
 {
     public abstract class ExtendableMessage<TMessage, TBuilder> : GeneratedMessage<TMessage, TBuilder>
         where TMessage : GeneratedMessage<TMessage, TBuilder>
-        where TBuilder : GeneratedBuilder<TMessage, TBuilder>
+        where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
     {
         protected ExtendableMessage()
         {

+ 1 - 1
src/ProtocolBuffers/GeneratedBuilder.cs

@@ -49,7 +49,7 @@ namespace Google.ProtocolBuffers
     /// </summary>
     public abstract class GeneratedBuilder<TMessage, TBuilder> : AbstractBuilder<TMessage, TBuilder>
         where TMessage : GeneratedMessage<TMessage, TBuilder>
-        where TBuilder : GeneratedBuilder<TMessage, TBuilder>
+        where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
     {
         /// <summary>
         /// Returns the message being built at the moment.

+ 31 - 1
src/ProtocolBuffers/GeneratedMessage.cs

@@ -50,7 +50,7 @@ namespace Google.ProtocolBuffers
     /// </summary>
     public abstract class GeneratedMessage<TMessage, TBuilder> : AbstractMessage<TMessage, TBuilder>
         where TMessage : GeneratedMessage<TMessage, TBuilder>
-        where TBuilder : GeneratedBuilder<TMessage, TBuilder>
+        where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new()
     {
         private UnknownFieldSet unknownFields = UnknownFieldSet.DefaultInstance;
 
@@ -175,5 +175,35 @@ namespace Google.ProtocolBuffers
         {
             unknownFields = fieldSet;
         }
+
+        public static TMessage ParseFromJson(string jsonText)
+        {
+            return Serialization.JsonFormatReader.CreateInstance(jsonText)
+                .Merge(new TBuilder())
+                .Build();
+        }
+
+        public static TMessage ParseFromJson(System.IO.TextReader reader)
+        { return ParseFromJson(reader, ExtensionRegistry.Empty); }
+
+        public static TMessage ParseFromJson(System.IO.TextReader reader, ExtensionRegistry extensionRegistry)
+        {
+            return Serialization.JsonFormatReader.CreateInstance(reader)
+                .Merge(new TBuilder(), extensionRegistry)
+                .Build();
+        }
+
+        public static TMessage ParseFromXml(System.Xml.XmlReader reader)
+        { return ParseFromXml(Serialization.XmlFormatReader.DefaultRootElementName, reader, ExtensionRegistry.Empty); }
+        
+        public static TMessage ParseFromXml(string rootElementName, System.Xml.XmlReader reader)
+        { return ParseFromXml(rootElementName, reader, ExtensionRegistry.Empty); }
+
+        public static TMessage ParseFromXml(string rootElementName, System.Xml.XmlReader reader, ExtensionRegistry extensionRegistry)
+        {
+            return Serialization.XmlFormatReader.CreateInstance(reader)
+                .Merge(rootElementName, new TBuilder(), extensionRegistry)
+                .Build();
+        }
     }
 }

+ 18 - 0
src/ProtocolBuffers/IMessage.cs

@@ -184,6 +184,24 @@ namespace Google.ProtocolBuffers
         /// </summary>
         new byte[] ToByteArray();
 
+        /// <summary>
+        /// Serializes the message to JSON text.  This is a trivial wrapper 
+        /// around Serialization.JsonFormatWriter.WriteMessage.
+        /// </summary>
+        string ToJson();
+
+        /// <summary>
+        /// Serializes the message to XML text.  This is a trivial wrapper 
+        /// around Serialization.XmlFormatWriter.WriteMessage.
+        /// </summary>
+        string ToXml();
+
+        /// <summary>
+        /// Serializes the message to XML text using the element name provided.
+        /// This is a trivial wrapper around Serialization.XmlFormatWriter.WriteMessage.
+        /// </summary>
+        string ToXml(string rootElementName);
+
         /// <summary>
         /// Serializes the message and writes it to the given stream.
         /// This is just a wrapper around WriteTo(ICodedOutputStream). This

+ 7 - 1
src/ProtocolBuffers/Serialization/XmlFormatWriter.cs

@@ -20,7 +20,13 @@ namespace Google.ProtocolBuffers.Serialization
 
         static XmlWriterSettings DefaultSettings(Encoding encoding)
         {
-            return new XmlWriterSettings() { CheckCharacters = false, NewLineHandling = NewLineHandling.Entitize, Encoding = encoding };
+            return new XmlWriterSettings() 
+            { 
+                CheckCharacters = false, 
+                NewLineHandling = NewLineHandling.Entitize, 
+                OmitXmlDeclaration = true,
+                Encoding = encoding, 
+            };
         }
 
         /// <summary>