c# - JavaScriptSerializer.Deserialize() skip property if cannot parse it -
i deserializing json strings using person
objects using code:
javascriptserializer serializer = new javascriptserializer(); person person = serializer.deserialize<person>(jsonstring);
the person
class has age property:
int age {get;set;}
the json string has value like:
{age: 'not valid int'}
and getting exception follows:
cannot cast string int32
is there way tell javascriptserializer
skip on error , continue other properties?
yes, possible control deserialization process writing custom javascriptconverter class:
public class personconverter : javascriptconverter { public override object deserialize(idictionary<string, object> dictionary, type type, javascriptserializer serializer) { person person = new person(); foreach (string key in dictionary.keys) { var value = dictionary[key]; switch (key) { case "name": person.name = (string)value; break; case "age": { if (value int) { person.age = (int)value; } else { int age; if (int.tryparse((string)dictionary[key], out age)) { person.age = age; } // else leave age null (or if int, leave 0); alternatively put else block here set value of choice } } break; } } return person; } public override idictionary<string, object> serialize(object obj, javascriptserializer serializer) { throw new notimplementedexception(); } public override ienumerable<type> supportedtypes { { return new[] { typeof(person) }; } } }
i have taken liberty of making person.age
nullable, null
indicates age unknown, if not acceptable modify converter default 0 or -1 when age not parseable:
public class person { public string name { get; set; } public int? age { get; set; } }
usage:
var serializer = new javascriptserializer(); serializer.registerconverters(new[] { new personconverter() }); var person = serializer.deserialize<person>(jsonstring);
example output:
var serializer = new javascriptserializer(); serializer.registerconverters(new[] { new personconverter() }); var jsonstrings = new list<string> { "{ name: 'steve', age: 21 }", "{ name: 'teoman', age: 'not valid int'}", "{ name: 'queen elizabeth ii', age: '89'}" }; foreach (var jsonstring in jsonstrings) { var person = serializer.deserialize<person>(jsonstring); console.writeline("name: {0}, age: {1}", person.name, person.age); }
name: steve, age: 21
name: teoman, age:
name: queen elizabeth ii, age: 89
please note have handled here: literal number, number inside string, , totally invalid value.
Comments
Post a Comment