I have this question and i am wondering if a possible solution can be adding attribute tags to say the object[][] maps to MyType[] where element 1 is MyType.IntName and element 2 is MyType.HtmlSz
Is it possible in any json solution on .NET?
I have this question and i am wondering if a possible solution can be adding attribute tags to say the object[][] maps to MyType[] where element 1 is MyType.IntName and element 2 is MyType.HtmlSz
Is it possible in any json solution on .NET?
It is possible with using of JavaScriptConverter
. You should define class MyType
like following:
public class MyType {
public string IntName { get; set; }
public int HtmlSz1 { get; set; }
public int HtmlSz2 { get; set; }
}
and the class MyTypeConverter
like
public class MyTypeConverter : JavaScriptConverter {
public override IEnumerable<Type> SupportedTypes {
get {
return new ReadOnlyCollection<Type> (new Type[] { typeof (MyType[]) });
}
}
public override object Deserialize (IDictionary<string, object> dictionary,
Type type, JavaScriptSerializer serializer) {
if (dictionary == null)
throw new ArgumentNullException ("dictionary");
if (type == typeof (MyType[])) {
ArrayList itemsList = (ArrayList)dictionary["resources"];
MyType[] res = new MyType[itemsList.Count];
for (int i = 0; i < itemsList.Count; i++) {
ArrayList entry = (ArrayList)itemsList[i];
res[i] = new MyType () {
HtmlSz1 = (int)entry[0],
HtmlSz2 = (int)entry[1],
IntName = (string)entry[2]
};
}
return res;
}
return null;
}
public override IDictionary<string, object> Serialize (object obj,
JavaScriptSerializer serializer) {
throw new InvalidOperationException ("We only Deserialize");
}
}
Then you can convert you input data with respect of following simple code:
JavaScriptSerializer serializer = new JavaScriptSerializer ();
serializer.RegisterConverters (new JavaScriptConverter[] { new MyTypeConverter () });
MyType[] res = serializer.Deserialize<MyType[]> (
@"{""resources"": [[123,567,""<div ...""],[456,789,""<table ...""]]}");