I have below class
[Serializable]
public class filters
{
public List<string> key1 { get; set; }
public List<string> key2 { get; set; }
public List<string> key3 { get; set; }
}
and json string is
[{"key1": "key1value"}]
deserializing like
filters objFilter = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<filters>(json);
json string may contain key1, key2 and key3 or may not.
key1, key2, key3 may be a single string or array
So how can i deserialize it.
It is throwing an error mostly.
class is not supported for deserialization of an array
Please advise Thanks
Your problem is that your JSON has properties whose values can either be strings or arrays of strings, like so:
To parse this you have chosen to use
JavaScriptSerializer
which is a very simple reflection-based serializer. Its ability to customize the mapping between objects and JSON is limited. Nevertheless you can write aJavaScriptConverter
for yourfilters
class that tests to see whether values of the"keyX"
properties are single items or arrays, and deserialize appropriately:Also, your root JSON container is an array rather than a object (i.e. the outer delimiters are
[]
not{}
), so you need to deserialize it as aList<filters>
.Thus:
This outputs
[{"key1":"key1value","key2":"key2value","key3":["key3value1","key3value2"]}]
as desired.Another option would be to switch to Json.NET, which has much more flexible tools for mapping objects to JSON. See How to handle both a single item and an array for the same property using JSON.net for specific instructions.
The problem with your code is your json is incorrect
Take the following code in a console app and see what you get
Or change your json just to the following
The '[]' in your json is a represenation that it it is an array, so you are trying to deserialize an array to type filters
then your deserialize should work