0

I am working on an JSON API client. The goal is to create a base type with the methods ToJSON(..) and FromJSON(..), which subsequent classes can inherit from.

ToJSON(..) is relatively straight forward, following a blog article by Scott Guthrie (http://bit.ly/Ppgd3). I am struggling with the FromJSON(..). Here is the basic code:

public class BaseType { public virtual void FromJson(System.Type type, string input) { // What? How? } public virtual string ToJson() { JavaScriptSerializer serial = new JavaScriptSerializer(); return serial.Serialize(this); } public virtual string ToJson(string verb) { JavaScriptSerializer serial = new JavaScriptSerializer(); string value = serial.Serialize(this); return string.Concat("{", "\"", verb.Trim(), "\":", value, "}"); } } 

Now the way to do this is with Deserialize(..) and that works outside the class. My question is how to get the Deserialize(..) command below to work within the above class, under FromJSON(..), in a way that is inheritable.

public class InheritedObject : BaseType { } System.Web.Script.Serialization.JavaScriptSerializer serial = new System.Web.Script.Serialization.JavaScriptSerializer(); InheritedObject foo = serial.Deserialize<InheritedOjbect>(jsonString); 

The language is C#, framework is .NET 4.0, and IDE is Visual Studio 2012.

1
  • The from* methods are typically static, since they create a new object from the input Commented Feb 5, 2013 at 23:52

1 Answer 1

0

Generics would probably help in this case.

public virtual T FromJson<T>(string input) { JavaScriptSerializer serial = new JavaScriptSerializer(); return serial.Deserialize<T>(input); } 

You would have to define T at the class level like so:

public class BaseType<T> where T : new() 

Then inherit like so:

public class InheritedObject : BaseType<InheritedObject> 

Or, make the method static:

public static T FromJson<T>(string input) where T : new() { JavaScriptSerializer serial = new JavaScriptSerializer(); return serial.Deserialize<T>(input); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Which object is the virtual fromJson called on? It only makes sense to make it static
I gave both options in case we don't have all the facts, but from what I can see in the limited code provided, static makes more sense.