Converting boolean to int in json string - c#

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; }
}

Related

How to override JavaScriptSerializer.Deserialize<T>()

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

Issue with asigning Json to variables [duplicate]

In reference to this question:
How can I change property names when serializing with Json.net?
Sure, great, but can I have the cake and eat it?
What I'm looking for is an eye pleasing way have an alternate name for a property in such a way that the string may contain either.
Something like:
[BetterJsonProperty(PropertyName = "foo_bar")]
public string FooBar { get; set; }
Both
{
"FooBar": "yup"
}
and
{
"foo_bar":"uhuh"
}
would deserialize as expected.
As solution with no attribute would work or an attribute on the class like:
[AllowCStylePropertyNameAlternatives]
One way to accomplish this is to create a custom JsonConverter. The idea is to have the converter enumerate the JSON property names for objects we are interested in, strip the non-alphanumeric characters from the names and then try to match them up with the actual object properties via reflection. Here is how it might look in code:
public class LaxPropertyNameMatchingConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsClass;
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
PropertyInfo[] props = objectType.GetProperties();
JObject jo = JObject.Load(reader);
foreach (JProperty jp in jo.Properties())
{
string name = Regex.Replace(jp.Name, "[^A-Za-z0-9]+", "");
PropertyInfo prop = props.FirstOrDefault(pi =>
pi.CanWrite && string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
prop.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use the custom converter with a particular class, you can decorate that class with a [JsonConverter] attribute like this:
[JsonConverter(typeof(LaxPropertyNameMatchingConverter))]
public class MyClass
{
public string MyProperty { get; set; }
public string MyOtherProperty { get; set; }
}
Here is a simple demo of the converter in action:
class Program
{
static void Main(string[] args)
{
string json = #"
[
{
""my property"" : ""foo"",
""my-other-property"" : ""bar"",
},
{
""(myProperty)"" : ""baz"",
""myOtherProperty"" : ""quux""
},
{
""MyProperty"" : ""fizz"",
""MY_OTHER_PROPERTY"" : ""bang""
}
]";
List<MyClass> list = JsonConvert.DeserializeObject<List<MyClass>>(json);
foreach (MyClass mc in list)
{
Console.WriteLine(mc.MyProperty);
Console.WriteLine(mc.MyOtherProperty);
}
}
}
Output:
foo
bar
baz
quux
fizz
bang
While this solution should do the job in most cases, there is an even simpler solution if you are OK with the idea of changing the Json.Net source code directly. It turns out you can accomplish the same thing by adding just one line of code to the Newtonsoft.Json.Serialization.JsonPropertyCollection class. In this class, there is a method called GetClosestMatchProperty() which looks like this:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
At the point where this method is called by the deserializer, the JsonPropertyCollection contains all the properties from the class being deserialized, and the propertyName parameter contains the name of the JSON property name being matched. As you can see, the method first tries an exact name match, then it tries a case-insensitive match. So we already have a many-to-one mapping being done between the JSON and class property names.
If you modify this method to strip out all non-alphanumeric characters from the property name prior to matching it, then you can get the behavior you desire, without any special converters or attributes needed. Here is the modified code:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
propertyName = Regex.Replace(propertyName, "[^A-Za-z0-9]+", "");
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
Of course, modifying the source code has its problems as well, but I figured it was worth a mention.
Another way of accomplishing this is intercepting the serialization/deserialization process early, by doing some overrides the JsonReader and JsonWriter
public class CustomJsonWriter : JsonTextWriter
{
private readonly Dictionary<string, string> _backwardMappings;
public CustomJsonWriter(TextWriter writer, Dictionary<string, string> backwardMappings)
: base(writer)
{
_backwardMappings = backwardMappings;
}
public override void WritePropertyName(string name)
{
base.WritePropertyName(_backwardMappings[name]);
}
}
public class CustomJsonReader : JsonTextReader
{
private readonly Dictionary<string, string> _forwardMappings;
public CustomJsonReader(TextReader reader, Dictionary<string, string> forwardMappings )
: base(reader)
{
_forwardMappings = forwardMappings;
}
public override object Value
{
get
{
if (TokenType != JsonToken.PropertyName)
return base.Value;
return _forwardMappings[base.Value.ToString()];
}
}
}
After doing this, you can serialize by doing
var mappings = new Dictionary<string, string>
{
{"Property1", "Equivalent1"},
{"Property2", "Equivalent2"},
};
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder), mappings), your_object);
and deserialize by doing
var mappings = new Dictionary<string, string>
{
{"Equivalent1", "Property1"},
{"Equivalent2", "Property2"},
};
var txtReader = new CustomJsonReader(new StringReader(jsonString), mappings);
var your_object = JsonSerializer.Create().Deserialize<Your_Type>(txtReader);

How to handle deserialization of empty string into long in .NET?

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);

Alternate property name while deserializing

In reference to this question:
How can I change property names when serializing with Json.net?
Sure, great, but can I have the cake and eat it?
What I'm looking for is an eye pleasing way have an alternate name for a property in such a way that the string may contain either.
Something like:
[BetterJsonProperty(PropertyName = "foo_bar")]
public string FooBar { get; set; }
Both
{
"FooBar": "yup"
}
and
{
"foo_bar":"uhuh"
}
would deserialize as expected.
As solution with no attribute would work or an attribute on the class like:
[AllowCStylePropertyNameAlternatives]
One way to accomplish this is to create a custom JsonConverter. The idea is to have the converter enumerate the JSON property names for objects we are interested in, strip the non-alphanumeric characters from the names and then try to match them up with the actual object properties via reflection. Here is how it might look in code:
public class LaxPropertyNameMatchingConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsClass;
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
PropertyInfo[] props = objectType.GetProperties();
JObject jo = JObject.Load(reader);
foreach (JProperty jp in jo.Properties())
{
string name = Regex.Replace(jp.Name, "[^A-Za-z0-9]+", "");
PropertyInfo prop = props.FirstOrDefault(pi =>
pi.CanWrite && string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
prop.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use the custom converter with a particular class, you can decorate that class with a [JsonConverter] attribute like this:
[JsonConverter(typeof(LaxPropertyNameMatchingConverter))]
public class MyClass
{
public string MyProperty { get; set; }
public string MyOtherProperty { get; set; }
}
Here is a simple demo of the converter in action:
class Program
{
static void Main(string[] args)
{
string json = #"
[
{
""my property"" : ""foo"",
""my-other-property"" : ""bar"",
},
{
""(myProperty)"" : ""baz"",
""myOtherProperty"" : ""quux""
},
{
""MyProperty"" : ""fizz"",
""MY_OTHER_PROPERTY"" : ""bang""
}
]";
List<MyClass> list = JsonConvert.DeserializeObject<List<MyClass>>(json);
foreach (MyClass mc in list)
{
Console.WriteLine(mc.MyProperty);
Console.WriteLine(mc.MyOtherProperty);
}
}
}
Output:
foo
bar
baz
quux
fizz
bang
While this solution should do the job in most cases, there is an even simpler solution if you are OK with the idea of changing the Json.Net source code directly. It turns out you can accomplish the same thing by adding just one line of code to the Newtonsoft.Json.Serialization.JsonPropertyCollection class. In this class, there is a method called GetClosestMatchProperty() which looks like this:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
At the point where this method is called by the deserializer, the JsonPropertyCollection contains all the properties from the class being deserialized, and the propertyName parameter contains the name of the JSON property name being matched. As you can see, the method first tries an exact name match, then it tries a case-insensitive match. So we already have a many-to-one mapping being done between the JSON and class property names.
If you modify this method to strip out all non-alphanumeric characters from the property name prior to matching it, then you can get the behavior you desire, without any special converters or attributes needed. Here is the modified code:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
propertyName = Regex.Replace(propertyName, "[^A-Za-z0-9]+", "");
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
Of course, modifying the source code has its problems as well, but I figured it was worth a mention.
Another way of accomplishing this is intercepting the serialization/deserialization process early, by doing some overrides the JsonReader and JsonWriter
public class CustomJsonWriter : JsonTextWriter
{
private readonly Dictionary<string, string> _backwardMappings;
public CustomJsonWriter(TextWriter writer, Dictionary<string, string> backwardMappings)
: base(writer)
{
_backwardMappings = backwardMappings;
}
public override void WritePropertyName(string name)
{
base.WritePropertyName(_backwardMappings[name]);
}
}
public class CustomJsonReader : JsonTextReader
{
private readonly Dictionary<string, string> _forwardMappings;
public CustomJsonReader(TextReader reader, Dictionary<string, string> forwardMappings )
: base(reader)
{
_forwardMappings = forwardMappings;
}
public override object Value
{
get
{
if (TokenType != JsonToken.PropertyName)
return base.Value;
return _forwardMappings[base.Value.ToString()];
}
}
}
After doing this, you can serialize by doing
var mappings = new Dictionary<string, string>
{
{"Property1", "Equivalent1"},
{"Property2", "Equivalent2"},
};
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder), mappings), your_object);
and deserialize by doing
var mappings = new Dictionary<string, string>
{
{"Equivalent1", "Property1"},
{"Equivalent2", "Property2"},
};
var txtReader = new CustomJsonReader(new StringReader(jsonString), mappings);
var your_object = JsonSerializer.Create().Deserialize<Your_Type>(txtReader);

deserializing json object with nested lists

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.

Categories