I have an object that contains nested lists and a method to deserialize it from json using custom converters and .net's javascript serializer. Something like this:
public class MyObject{
int TheID { get; set; }
public List<MyNestedObject1> ListOfMyNestedObject1 { get; set; }
public List<MyNestedObject2> ListOfMyNestedObject2 { get; set; }
public MyObject ObjectFromJson(string TheObjectInJson) {
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyObjectConvert()
});
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyNestedObject1Convert()
});
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyNestedObject2Convert()
});
//if I comment out the registrations of the converters, it works
//but I need the converters of the nested objects to kick in
return TheSerializer.Deserialize<MyObject>(TheObjectInJson);
}
}
The json converters for the nested objects both look like this:
public class MyNestedObject1Convert : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes {
get { return new Type[] { typeof(MyNestedObject1Convert) };
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{ //deserialization logic
return MyNestedObject1;}
}
And the converter for MyObject looks like this:
public class MyObjectConvert : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(MyObjectConvert) }; }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
int TheID;
MyObject TheObject = new MyObject();
int.TryParse(serializer.ConvertToType<string>(dictionary["TheID"]), out TheID))
TheObject.ID = TheID;
return TheObject;
}
}
Now the calling function that receives the json string and looks to return the c# object looks like this:
MyObject AMyObject = new MyObject();
MyObject TheMyObject = new MyObject();
TheMyObject = AMyObject.ObjectFromJson(JsonString);
When I run this code, the returned object contains TheID but the nested objects are null. I'm registering the converters in the object method but I'm guessing that's not the way to do it. If I remove the registration of the converters, the object DOES contain the nested objects, but then the converters don't kick in.
What do I need to change? Note: I'm not looking to use another library, just to make the native deserializer work.
Thanks for your suggestions.
Ok, so I got it to work. If you're looking to deserialize nested lists, this is how you do it.
First, don't register the converters in the MyObject ObjectFromJson method.
Second, it's in the custom converter of MyObject that you do the deserialization of the nested lists. Like this:
public class MyObjectConvert : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes { get { return new Type[] { typeof(MyObjectConvert) }; }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
int TheID;
MyObject TheObject = new MyObject();
int.TryParse(serializer.ConvertToType<string>(dictionary["TheID"]), out TheID))
TheObject.ID = TheID;
if (dictionary.ContainsKey("ListOfMyNestedObject1"))
{
serializer.RegisterConverters(new JavaScriptConverter[] { new MyNestedObject1Convert() });
var TheList = serializer.ConvertToType<List<MyNestedObject1>>(dictionary["ListOfMyNestedObject1"]);
TheObject.ListOfMyNestedObject1 = TheList
}
return TheObject;
}
}
And voila: json deserialization of nested lists with .net's javascriptserializer using custom javascript converters.
Related
So let's say I have a:
List<IInterface> list;
that has been serialized with TypeNameHandling.Auto, so it has "dynamic" type information. I can deserialize it fine as Newtonsoft.Json can recognize the type from the $type and Json can use the correct constructor. So far so good.
Now say I want to override the creation converter with a mehtod:
CustomCreationConverter<IInterface>
that overrides the creation of the object:
public override IInterface Create(Type objectType)
At this point objectType will always be IInterface and not a derived implementation, so I have no way to create the correct object. The meta-information of $type is now lost.
Is there an elegant way to fix this?
Here would be an attempt that does not work:
public class CustomConverter : CustomCreationConverter<Example.IInterface> {
public override Example.IInterface Create(Type objectType) {
return Example.MakeObject(objectType); // this won't work, objectType will always be IInterface
}
}
public class Example {
public interface IInterface { };
public class A : IInterface { public int content; };
public class B : IInterface { public float data; };
public static IInterface MakeObject(Type t) {
if (t == typeof(IInterface)) {
throw new Exception();
}
return t == typeof(A) ? new A() : new B();
}
public static void Serialize() {
var settings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.Auto
};
JsonSerializer serializer = JsonSerializer.Create(settings);
// serializer.Converters.Add(new CustomConverter()); // ?? can't have both, either CustomConverter or $type
List<IInterface> list = new() { MakeObject(typeof(A)), MakeObject(typeof(B)) };
using (StreamWriter sw = new("example.json")) {
serializer.Serialize(sw, list);
}
// Now read back example.json into a List<IInterface> using MakeObject
// Using CustomConverter won't work
using (JsonTextReader rd = new JsonTextReader(new StreamReader("example.json"))) {
List<IInterface> list2 = serializer.Deserialize<List<IInterface>>(rd);
}
}
}
Once you provide a custom converter such as CustomCreationConverter<T> for a type, the converter is responsible for all the deserialization logic including logic for type selection logic that would normally be implemented by TypeNameHandling. If you only want to inject a custom factory creation method and leave all the rest of the deserialization logic unchanged, you could create your own custom contract resolver and inject the factory method as JsonContract.DefaultCreator.
To implement this, first define the following factory interface and contract resolver:
public interface IObjectFactory<out T>
{
bool CanCreate(Type type);
T Create(Type type);
}
public class ObjectFactoryContractResolver : DefaultContractResolver
{
readonly IObjectFactory<object> factory;
public ObjectFactoryContractResolver(IObjectFactory<object> factory) => this.factory = factory ?? throw new ArgumentNullException(nameof(factory));
protected override JsonContract CreateContract(Type objectType)
{
var contract = base.CreateContract(objectType);
if (factory.CanCreate(objectType))
{
contract.DefaultCreator = () => factory.Create(objectType);
contract.DefaultCreatorNonPublic = false;
}
return contract;
}
}
Next, refactor your IInterface class hierarchy to make use of an IObjectFactory as an object creation factory:
public class InterfaceFactory : IObjectFactory<IInterface>
{
public InterfaceFactory(string runtimeId) => this.RuntimeId = runtimeId; // Some value to inject into the constructor
string RuntimeId { get; }
public bool CanCreate(Type type) => !type.IsAbstract && typeof(IInterface).IsAssignableFrom(type);
public IInterface Create(Type type) => type switch
{
var t when t == typeof(A) => new A(RuntimeId),
var t when t == typeof(B) => new B(RuntimeId),
_ => throw new NotImplementedException(type.ToString()),
};
}
public interface IInterface
{
public string RuntimeId { get; }
}
public class A : IInterface
{
[JsonIgnore] public string RuntimeId { get; }
internal A(string id) => this.RuntimeId = id;
public int content { get; set; }
}
public class B : IInterface
{
[JsonIgnore] public string RuntimeId { get; }
internal B(string id) => this.RuntimeId = id;
public float data { get; set; }
}
(Here RuntimeId is some value that needs to be injected during object creation.)
Now you will be able to construct your list as follows:
var valueToInject = "some value to inject";
var factory = new InterfaceFactory(valueToInject);
List<IInterface> list = new() { factory.Create(typeof(A)), factory.Create(typeof(B)) };
And serialize and deserialize as follows:
var resolver = new ObjectFactoryContractResolver(factory)
{
// Set any necessary properties e.g.
NamingStrategy = new CamelCaseNamingStrategy(),
};
var settings = new JsonSerializerSettings
{
ContractResolver = resolver,
TypeNameHandling = TypeNameHandling.Auto,
};
var json = JsonConvert.SerializeObject(list, Formatting.Indented, settings);
var list2 = JsonConvert.DeserializeObject<List<IInterface>>(json, settings);
Notes:
Newtosoft recommends that you cache and reuse your contract resolvers for best performance.
Newtonsoft also recommends that
TypeNameHandling should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a custom SerializationBinder when deserializing with a value other than None.
For why, see e.g. TypeNameHandling caution in Newtonsoft Json or External json vulnerable because of Json.Net TypeNameHandling auto?.
Demo fiddle here.
I'm very new with JSON, please help!
I am trying to serialise a List<KeyValuePair<string, string>> as JSON
Currently:
[{"Key":"MyKey 1","Value":"MyValue 1"},{"Key":"MyKey 2","Value":"MyValue 2"}]
Expected:
[{"MyKey 1":"MyValue 1"},{"MyKey 2":"MyValue 2"}]
I referred to some examples from this and this.
This is my KeyValuePairJsonConverter : JsonConverter
public class KeyValuePairJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
List<KeyValuePair<object, object>> list = value as List<KeyValuePair<object, object>>;
writer.WriteStartArray();
foreach (var item in list)
{
writer.WriteStartObject();
writer.WritePropertyName(item.Key.ToString());
writer.WriteValue(item.Value.ToString());
writer.WriteEndObject();
}
writer.WriteEndArray();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(List<KeyValuePair<object, object>>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var target = Create(objectType, jsonObject);
serializer.Populate(jsonObject.CreateReader(), target);
return target;
}
private object Create(Type objectType, JObject jsonObject)
{
if (FieldExists("Key", jsonObject))
{
return jsonObject["Key"].ToString();
}
if (FieldExists("Value", jsonObject))
{
return jsonObject["Value"].ToString();
}
return null;
}
private bool FieldExists(string fieldName, JObject jsonObject)
{
return jsonObject[fieldName] != null;
}
}
I am calling it from a WebService method like this
List<KeyValuePair<string, string>> valuesList = new List<KeyValuePair<string, string>>();
Dictionary<string, string> valuesDict = SomeDictionaryMethod();
foreach(KeyValuePair<string, string> keyValue in valuesDict)
{
valuesList.Add(keyValue);
}
JsonSerializerSettings jsonSettings = new JsonSerializerSettings { Converters = new [] {new KeyValuePairJsonConverter()} };
string valuesJson = JsonConvert.SerializeObject(valuesList, jsonSettings);
You can use Newtonsoft and dictionary:
var dict = new Dictionary<int, string>();
dict.Add(1, "one");
dict.Add(2, "two");
var output = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
The output is :
{"1":"one","2":"two"}
Edit
Thanks to #Sergey Berezovskiy for the information.
You are currently using Newtonsoft, so just change your List<KeyValuePair<object, object>> to Dictionary<object,object> and use the serialize and deserialize method from the package.
So I didn't want to use anything but native c# to solve a similar issue and for reference this was using .net 4, jquery 3.2.1 and backbone 1.2.0.
My issues was that the List<KeyValuePair<...>> would process out of the controller into a backbone model but when I saved that model the controller could not bind List.
public class SomeModel {
List<KeyValuePair<int, String>> SomeList { get; set; }
}
[HttpGet]
SomeControllerMethod() {
SomeModel someModel = new SomeModel();
someModel.SomeList = GetListSortedAlphabetically();
return this.Json(someModel, JsonBehavior.AllowGet);
}
network capture:
"SomeList":[{"Key":13,"Value":"aaab"},{"Key":248,"Value":"aaac"}]
But even though this set SomeList properly in the backing model.js trying to save the model without any changes to it would cause the binding SomeModel object to have the same length as the parameters in the request body but all the keys and values were null:
[HttpPut]
SomeControllerMethod([FromBody] SomeModel){
SomeModel.SomeList; // Count = 2, all keys and values null.
}
The only things I could find is that KeyValuePair is a structure and not something that can be instantiated in this manner. What I ended up doing is the following:
Add a Model wrapper somewhere that contains key, value fields:
public class KeyValuePairWrapper {
public int Key { get; set; }
public String Value { get; set; }
//default constructor will be required for binding, the Web.MVC binder will invoke this and set the Key and Value accordingly.
public KeyValuePairWrapper() { }
//a convenience method which allows you to set the values while sorting
public KeyValuePairWrapper(int key, String value)
{
Key = key;
Value = value;
}
}
Set up your binding class model to accept your custom wrapper object.
public class SomeModel
{
public List<KeyValuePairWrapper> KeyValuePairList{ get; set };
}
Get some json data out of a controller
[HttpGet]
SomeControllerMethod() {
SomeModel someModel = new SomeModel();
someModel.KeyValuePairList = GetListSortedAlphabetically();
return this.Json(someModel, JsonBehavior.AllowGet);
}
Do something at a later time, maybe model.save(null, ...) is invoked
[HttpPut]
SomeControllerMethod([FromBody] SomeModel){
SomeModel.KeyValuePairList ; // Count = 2, all keys and values are correct.
}
I there,
I'm working on a c# application
I Have a situation where i get an object from a web service, say
MyObject{
public bool MyProp
}
And I can't modify that object,
but i need to serialize MyObject to a json string but MyProp has to be converted to 1 or 0 instead of true/false.
I'm using JavaScriptSerializer to serialize to Json
Any idea?
tks
If you are willing to switch to json.net, you can use the solution from Convert an int to bool with Json.Net.
If you wish to continue using JavaScriptSerializer, you will need to create a JavaScriptConverter for your MyObject type as follows:
class MyObjectConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(MyObject) }; }
}
// Custom conversion code below
const string myPropName = "MyProp";
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
object value;
if (dictionary.TryGetValue(myPropName, out value))
{
dictionary[myPropName] = !value.IsNullOrDefault();
}
var myObj = new JavaScriptSerializer().ConvertToType<MyObject>(dictionary);
return myObj;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var myObj = (MyObject)obj;
// Generate a default serialization. Is there an easier way to do this?
var defaultSerializer = new JavaScriptSerializer();
var dict = defaultSerializer.Deserialize<Dictionary<string, object>>(defaultSerializer.Serialize(obj));
dict[myPropName] = myObj.MyProp ? 1 : 0;
return dict;
}
}
public static class ObjectExtensions
{
public static bool IsNullOrDefault(this object value)
{
// Adapted from https://stackoverflow.com/questions/6553183/check-to-see-if-a-given-object-reference-or-value-type-is-equal-to-its-default
if (value == null)
return true;
Type type = value.GetType();
if (!type.IsValueType)
return false; // can't be, as would be null
if (Nullable.GetUnderlyingType(type) != null)
return false; // ditto, Nullable<T>
object defaultValue = Activator.CreateInstance(type); // must exist for structs
return value.Equals(defaultValue);
}
}
Then use it like:
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyObjectConverter() } );
var json = serializer.Serialize(myObject);
Note - even though your MyObject class only has one property, I wrote the converter under the assumption that in real life it could have additional properties that should be serialized and deserialized automatically, for instance:
public class MyObject
{
public bool MyProp { get; set; }
public string SomeOtherProperty { get; set; }
}
I get a json string which have few data uniformity issue.
For example one field in json string returns a list of string while the same field in other json string returns a dictionary(key, value pairs).
My class which holds the parsed json values have property for the field as List.
Because of this data uniformity problem, the json string is not parsed properly.
Following is my code to parse the json string
JavaScriptSerializer serializer = new JavaScriptSerializer();
myClass mc = serializer.Deserialize<myClass>(jsonString);
IS there any way with which i can write custom code to parse the json string and map it to myClass?
You don't give a concrete example of what you are trying to accomplish, which means we need to make up an example ourselves. Consider the following class:
public class myClass
{
public Dictionary<string, string> data { get; set; }
}
And consider the following two JSON strings:
{"data": ["zero", 1, "two"]}
{"data": {"0": "zero", "1":1, "2":"two"}}
It seems like you might like to parse these identically, with the array being converted to a Dictionary<string, string> whose keys are array indices. This can be accomplished with the following JavaScriptConverter:
public class myClassConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
var myClass = new myClass();
object data;
if (dictionary.TryGetValue("data", out data))
{
if (data.IsJsonArray())
{
myClass.data = data.AsJsonArray()
.Select((o, i) => new KeyValuePair<int, object>(i, o))
.ToDictionary(p => p.Key.ToString(NumberFormatInfo.InvariantInfo), p => serializer.ConvertToType<string>(p.Value));
}
else if (data.IsJsonObject())
{
myClass.data = data.AsJsonObject()
.ToDictionary(p => p.Key, p => serializer.ConvertToType<string>(p.Value));
}
}
return myClass;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new [] { typeof(myClass) }; }
}
}
public static class JavaScriptSerializerObjectExtensions
{
public static bool IsJsonArray(this object obj)
{
if (obj is string || obj.IsJsonObject())
return false;
return obj is IEnumerable;
}
public static IEnumerable<object> AsJsonArray(this object obj)
{
return (obj as IEnumerable).Cast<object>();
}
public static bool IsJsonObject(this object obj)
{
return obj is IDictionary<string, object>;
}
public static IDictionary<string, object> AsJsonObject(this object obj)
{
return obj as IDictionary<string, object>;
}
}
The IDictionary<string, object> passed to Deserialize() corresponds to the key/value pairs in the JSON object being converted. For a particular key ("data" in this case) the object value will be an IDictionary<string, object> if the value is, in turn, a JSON object, and an IEnumerable (specifically an ArrayList) if the value is a JSON array. By testing the value against the appropriate type, a conversion can be made.
The converter only does deserialization. Use it like so:
var jsonString1 = #"{""data"": [""zero"", 1, ""two""]}";
var jsonString2 = #"{""data"": {""0"": ""zero"", ""1"":1, ""2"":""two""}}";
var deserializer = new JavaScriptSerializer();
deserializer.RegisterConverters(new JavaScriptConverter[] { new myClassConverter() });
var newJson1 = new JavaScriptSerializer().Serialize(deserializer.Deserialize<myClass>(jsonString1));
var newJson2 = new JavaScriptSerializer().Serialize(deserializer.Deserialize<myClass>(jsonString2));
Console.WriteLine(newJson1); // Prints {"data":{"0":"zero","1":"1","2":"two"}}
Console.WriteLine(newJson2); // Prints {"data":{"0":"zero","1":"1","2":"two"}}
Debug.Assert(newJson1 == newJson2); // No assert
The below illustration represents building Object of type TestClass2 using object of type TestClass1 with the help of Serialization/Deserialization.
TestClass1 and TestClass2 have the same structure except one of the members is string in TestClass1 but long in TestClass2.
public class TestClass1
{
public string strlong;
}
public class TestClass2
{
public long strlong;
}
TestClass1 objT1 = new TestClass1();
objT1.strlong = "20134567";
TestClass2 objT2;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string JSON1 = serializer.Serialize(objT1);
objT2 = serializer.Deserialize<TestClass2>(JSON1);
After the operation, objT2 will have the values of objT1 but strlong will now be long as opposed to string.
The problem is, if the strlong value in objT1 is an empty string --> "", the deserialization fails with an exception "" is not a valid value for Int64.
If strlong is non empty string with just numeric characters, the current deserialization works. But I do not know the workaround when something like empty string appears.
For now, lets assume that
strlong will be in the range of long
Will just be a sequence of numeric characters i.e. it will not have . or , or / or any type of other characters
Have access to only objects for serialization and I cannot make modifications to TestClass1 or TestClass2.
If there is a simple way (or not) of Creating objects of one class using objects of another class, please mention that in the comments.
EDIT-Extending the logic
To extend the logic of solution given in the Answer below to Classes containing members of type other classes, I have used the serialization solution given below to the member items as well. In other words, if classes contain members of other classes, is there a better way of handling the deeper levels than the code below?
// **Item1 :**
// These are the subclasses and classes
// whose objects I am trying to serialize
// and deserialize from one type to another
public class SubClass1
{
public string toomuch;
public int number = 30;
}
public class SubClass2
{
public long toomuch;
public int number;
}
public class TestClass1
{
public string strlong;
public SubClass1 item2;
}
public class TestClass2
{
public long strlong;
public SubClass2 item2;
}
// **Item2 :**
// Solution from StackOverflow for serialization of
// empty string
public class TestClass1Converter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(TestClass1) }; }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var data = obj as TestClass1;
var dic = new Dictionary<string, object>();
if (data == null)
{
return dic;
}
long val = 0;
long.TryParse(data.strlong, out val);
dic.Add("strlong", val);
// **Item3 :**
// trying to serialize and deserialize item2 which is of type SubClass1
// which might also have empty string
/*******************/
JavaScriptSerializer subClassSerializer = new JavaScriptSerializer();
subClassSerializer.RegisterConverters(new[] { new SubClass1Converter() });
string JSONstr = subClassSerializer.Serialize(data.item2);
dic.Add("item2", subClassSerializer.Deserialize<SubClass2>(JSONstr));
/*******************/
return dic;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
}
// **Item4 :**
// Serialization for subclass
public class SubClass1Converter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(SubClass1) }; }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var data = obj as SubClass1;
var dic = new Dictionary<string, object>();
if (data == null)
{
return dic;
}
long val = 0;
long.TryParse(data.toomuch, out val);
dic.Add("toomuch", val);
dic.Add("number", data.number);
return dic;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
TestClass1 objT1 = new TestClass1();
objT1.strlong = "";
SubClass1 objSub = new SubClass1();
objSub.toomuch = "";
objT1.item2 = objSub;
TestClass2 objT2;
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new TestClass1Converter() });
string JSON1 = serializer.Serialize(objT1);
objT2 = serializer.Deserialize<TestClass2>(JSON1);
}
}
You should declare your TestClass2.strlong as nullable.
public class TestClass2
{
public long? strlong;
}
Now you can have null in case when the TestClass1.strlong is empty string or null.
Here is UPDATE in case that you haven't access to modify the classes.
You should add to the serializer the converter via RegisterConverters to customize conversion. Here is the example:
public class TestClass1Converter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(TestClass1)}; }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var data = obj as TestClass1;
var dic = new Dictionary<string, object>();
if(data == null)
{
return dic;
}
long val = 0;
long.TryParse(data.strlong, out val);
dic.Add("strlong", val);
return dic;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
}
This converter will serialize strlong to 0 in case when it is not convertible to long. You can use it in this way:
TestClass1 objT1 = new TestClass1();
objT1.strlong = "444";
TestClass2 objT2;
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new [] {new TestClass1Converter()});
string JSON1 = serializer.Serialize(objT1);
objT2 = serializer.Deserialize<TestClass2>(JSON1);