How to build DataContractJsonSerialize convenience function

Tags: json c#
By : RBS
Source: Stackoverflow.com
Question!

I have a common code of serializing a class object in my 3-4 methods ,So I am thinking to create a common function for that code and call function in all the methods

I am doingn this from the following code

DataContractJsonSerializer ser = new DataContractJsonSerializer(this.GetType());
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, this);

                json = Encoding.Default.GetString(ms.ToArray());

                ms.Close();

I want to put this common code in seprate general function which returns Json string and which accept whole class as input parameter as I am converting whole class into a Json object , I tried creating function like

public string GenerateJsonString(class C1)

but this is giving me error on the keyword "class" saying that type is required

Can anyone tell me how can I accept whole class object in seprate method or function

By : RBS


Answers

You are confusing a "class" with an "object". You serialize an object, which is an instance of a particular class (aka "Type").

You can create a method taking a parameter of the .NET base type for all objects, "object", like this:

public static string GenerateJsonString(object o) 
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
        ser.WriteObject(ms, o);
        json = Encoding.Default.GetString(ms.ToArray());
        ms.Close();
        return json;
    }
}


It's not clear what you mean by "class object". If you mean an object, passing a reference to the object as normal does pass "the whole object" (well, a reference to it). You can get at all the members.

If you want to pass the type itself, you should declare the parameter as Type - but I suspect that's not really what you want.

If you want to write a method which will accept any object, just declare the parameter as type Object:

public string GenerateJsonString(object x)

Personally I wouldn't use Encoding.Default (which is system-specific) to convert the binary to text, by the way - what encoding is the serializer really using? Does it let you pass in a TextWriter (e.g. a StringWriter) instead of a stream?

By : Jon Skeet


Try using Type instead of class

public string GenerateJsonString(Type t1)
By : JaredPar


This video can help you solving your question :)
By: admin