I have an issue while deserializing json data which can have both float or array type of data. The same issue from here Dealing with JSON field that holds different types in C#
But everywhere the solution is to use json.net with a JsonConverter
. I need to achieve the deserialization using only System.Web.Script.Serialization.JavaScriptSerializer
in c#. Can anyone help, pls?
You can use a
JavaScriptConverter
for this purpose. However, unlike Json.NET'sJsonConverter
aJavaScriptConverter
can only be used for types that map from and to a JSON object -- not an array or primitive type. Thus you will need to create a custom converter for any object that may contain a polymorphic property that could be an array or singleton item.Let's imagine you have JSON that looks like the following:
Where
"values"
might sometimes be a primitive value like so:And, you want to map this to the following POCO:
As
JavaScriptConverter.Deserialize()
is passed anIDictionary<string, object>
of parsed values, the steps to take are:Detach any properties that need custom processing (keeping in mind that
JavaScriptSerializer
is case-insensitive but that the dictionary is not).Generate a default deserialization for any remaining properties using
JavaScriptSerializer.ConvertToType<T>()
using a fresh serializer that does not contain the converter.Manually deserialize and populate the custom properties into the partially deserialized object, and return it.
For the type shown above, the following converter, based somewhat on this answer, does the job:
Then use it like: