How to create a convenience function DataContractJsonSerialize
I have generic code for serializing a class object in my 3-4 methods. So I'm going to create a generic function for this code and call functions in all methods
I am doing it 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 generic code in a separate generic function that returns a Json string and that takes the whole class as an input parameter, since I am converting the whole class to a Json object, I tried to create a function like
public string GenerateJsonString (class C1)
but this gives me an error on the keyword "class" saying that the type is required
Can anyone tell me how can I take an entire class object in a seprate method or function
source to share
You are confusing "class" with "object". You are serializing an object that is an instance of a specific class (aka "Type").
You can create a method that takes a .NET base type parameter for all object objects, for example:
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;
}
}
source to share
It is not clear what you mean by "class object". If you mean an object, passing an object reference, as usual, passes "the whole object" (well, a reference to it). You can get all members.
If you want to pass the type itself, you must declare the Type parameter - but I suspect not quite what you want.
If you want to write a method that accepts any object, simply declare the parameter as type Object :
public string GenerateJsonString(object x)
Personally, I wouldn't use Encoding.Default
(which is system-wide) to convert binary to text by the way - what encoding does the serializer actually use? Do you allow you to pass text to a TextWriter (like StringWriter) instead of a stream?
source to share