Reputation: 190907
Is there a way with the JavaScriptSerializer
(I don't want to use another library at this time) where I can do something like this?
class Model
{
string[] Values { get; set; }
}
// using the serializer
JavaScriptSerializer serializer = new JavaScriptSerializer();
// this works
Model workingModel = serializer.Deserialize<Model>("{ Values : ['1234', '2346'] }");
// this works
Model wontWorkModel = serializer.Deserialize<Model>("{ Values : 'test' }");
I want wontWorkModel.Values
to be an array with 1 item - test
.
Is this possible with the JSON I've specified?
Edit
I was able to hack this in using a TypeConverter
and inserting it into the type of string[]
, but it seems very hackish (and scary that I can do that in .NET).
Upvotes: 0
Views: 2360
Reputation: 63956
One option would be to create a JavascriptConverter as so:
public class ModelConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(Model))
{
Model result = new Model();
foreach (var item in dictionary.Keys)
{
if (dictionary[item] is string && item == "Values")
result.Values = new string[] { (string)dictionary[item] };
else if(item=="Values")
result.Values = (string[])((ArrayList)dictionary[item]).ToArray(typeof(string));
}
return result;
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(Model) })); }
}
}
You can call it like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
ModelConverter sc = new ModelConverter();
serializer.RegisterConverters(new JavaScriptConverter[] { new ModelConverter() });
Model workingModel = serializer.Deserialize<Model>("{ Values : '2346' }");
Model workingModel1 = serializer.Deserialize<Model>("{ Values : ['2346'] }");
Model workingModel2 = serializer.Deserialize<Model>("{ Values : ['2346','3123'] }");
Here's the MSDN documentation for JavascriptConverter
Upvotes: 1
Reputation: 932
Why not simply use
Model wontWorkModel = serializer.Deserialize<Model>("{ Values : ['test'] }");
Upvotes: 0