How to build DataContractJsonSerialize convenience function
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
Solution
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;
}
}
OTHER TIPS
Type the parameter as "object". You can't pass a class as a parameter, only an instance of a class - which in OOP is referred to as an "object"
public string GenerateJsonString(object obj)
If all the objects that you are passing to this method are instances of classes that derive from a common base class, then you can use polymorphism and write the method to accept objects that are instances of the base class. Otherwise, all classes are derived from System.Object
.
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?
You can accept an object. A class is not instantiated and there for cannot be passed to the method.
Try using Type instead of class
public string GenerateJsonString(Type t1)