Deserializing Single Object and Multiple Object using JSON Converter.
JSON Sample
this is Single Json Object
{ "Name":"Test", "Email":"Abc", "ID":1 }Multi Json Object
[ { "Name": "Test", "Email": "Abc", "ID": 1 }, { "Name": "Test1", "Email": "Abc1", "ID": 2 } ]
List<Employee> list = JsonConvert.DeserializeObject<List<Employee>>("string json Content");
Here if your JSON string contain single object that time it cause error like "'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'."
so to avoid this use the JSON Converter.
Example:
JsonSerializerSettings setting = new JsonSerializerSettings(); setting.Converters.Add(new SingleOrArrayConverter<Employee>()); List<Employee> list = JsonConvert.DeserializeObject<List<Employee>>("string json Content",setting);
Custom Class For Converting Object Result into JSON
Public class SingleOrArrayConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(List<T>)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); if (token.Type == JTokenType.Array) { return token.ToObject<List<T>>(); } return new List<T> { token.ToObject<T>() }; } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } }
No comments:
Post a Comment