none
C# Google Gson for REST

    Question

  • Hi C# Experts,

    Need to migrate from Java to C#/.NET Framework 2.0. The Java code extensively uses the Google Gson for REST. Please help with the corresponding library for C#, perhaps a Google Gson .NET library. The native System.Runtime.Serialization.Json (.NET 3.5) didn't help.

    Please help.

    Thanks



    • Edited by recherche Saturday, June 07, 2014 9:29 AM typo
    Friday, December 28, 2012 8:38 AM

Answers

All replies

  • Perhaps Json.NET? http://json.codeplex.com/
    • Marked as answer by recherche Friday, December 28, 2012 9:39 AM
    Friday, December 28, 2012 9:05 AM
    Moderator
  • Thank you.
    Friday, December 28, 2012 9:40 AM
  • How implement JSON using .NET framework, including byte[] and Datetime ISO8601

    In my opinion is better -and a good practice- to use Microsoft's framework because this platform have full Microsoft's support. Support is very important in serious enterprise projects.

    .NET framework not uses base64 codification for byte[] (neither GSON. For GSON it is possible to write an adapter in order to redefine the serialization and deserialization byte[] <--> base64)

    In the following example, I am implementing the same GSON functions toJson() and fromJson() using DataContractJsonSerializer of .NET and I am creating a DataContractSurrogate, in order to customize serialization and deserialization of one specific class (the which include, in this example, one field of type byte[]).

    Suppose that your class is "A", and the definition of this class at server side is the following: 

    class A
    {
      String s;
      int i;
      byte[] b;
      DateTime d;
    }

    In the client side, one inrtroduce a new field "_b" which actually contains the base64 data. The field "b" contains byte[]. Note that DataMember "_b" is renamed to "b" (the real name of the field in DataContract). Also, note that field "b" is not a DataMenber of DataContract (then, serialization/deserialization can not view field "b").

    Note that Datetime management between .NET and GSON are incompatible. In this example Datetime is managed using the format ISO8601 (you can note that ISO8601 is compatible with Javascript clients). If your server uses GSON you need to define the date format ISO8601 as follows: new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").

    // Program.cs
    // Carlos Pineda G. 
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.Serialization.Json;
    using System.Runtime.Serialization;
    using System.IO;
    using System.Collections.ObjectModel;

    [DataContract]
    class A
    {
        [DataMember]
        public String s;
        [DataMember]
        public int i;
        [DataMember(Name="b")]
        public String _b;
        public byte[] b;
        [DataMember]
        public DateTime d;
    }
    class DataContractSurrogate : IDataContractSurrogate
    {
        public Type GetDataContractType(Type type)
        {
            return type;
        }
        public Object GetObjectToSerialize(Object obj, Type targetType)
        {
            if (obj is A)
            {
                ((A)obj)._b = Convert.ToBase64String(((A)obj).b);
            }
            return obj;
        }
        public Object GetDeserializedObject(Object obj, Type targetType)
        {
            if (obj is A)
            {
                ((A)obj).b = Convert.FromBase64String(((A)obj)._b);
            }
            return obj;
        }
        public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, Object customData)
        {
            return null;
        }
        public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
        {
            return typeDeclaration;
        }
        public Object GetCustomDataToExport(Type clrType, Type dataContractType)
        {
            return null;
        }
        public Object GetCustomDataToExport(System.Reflection.MemberInfo memberInfo, Type dataContractType)
        {
            return null;
        }
        public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
        {
        }
    }

    class Program
    {
        // here it is necessary include the Type because "obj" could be null
        public static String toJson(Object obj,Type t)
        {
            DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
            settings.DateTimeFormat = new DateTimeFormat("yyyy-MM-ddTHH:mm:ss.fffzzz");
            settings.DataContractSurrogate = new DataContractSurrogate();
            DataContractJsonSerializer j = new DataContractJsonSerializer(t, settings);
            using (MemoryStream m = new MemoryStream())
            {
                j.WriteObject(m, obj);
                return Encoding.UTF8.GetString(m.ToArray());
            }
        }
        public static Object fromJson(String s, Type t)
        {
            DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
            settings.DateTimeFormat = new DateTimeFormat("yyyy-MM-ddTHH:mm:ss.fffzzz");
            settings.DataContractSurrogate = new DataContractSurrogate();
            DataContractJsonSerializer j = new DataContractJsonSerializer(t, settings);
            using (MemoryStream m = new MemoryStream(Encoding.UTF8.GetBytes(s)))
            {
                return j.ReadObject(m);
            }
        }
        static void Main()
        {
            A a = new A();
            a.b = new byte[] {65,66,67,68};
            a.s = "xyz";
            a.i = 12345;
            a.d = DateTime.Now;
            String s = toJson(a,typeof(A));
            Console.WriteLine(s);
            A a2 = (A)fromJson(s, typeof(A));
            Console.WriteLine(a2.s + " " + a2.i + " " + a2.b[0] + " " + a2.b[1] + " " + 
                                          a2.b[2] + " " + a2.b[3] + " " + a2.d);
        }
    }




    Thursday, June 05, 2014 5:30 AM