Though the ASP.NET 4.0 built in JSON to C# parsing/serialization works great and in most cases you can just define a simple C# class that models the "signature" of your JSON and get the correct C# representation of your JSON with a call to something like Test(MyCSharpJsonObj aa), you seem to need something more robust. Note with the code you are about to see below, don't think you can overload your functions like so Test(ListData1 aa), Test(ListData2 aa)
, ASP.NET won't correctly call the right function for you on request from client and may not even compile correctly, if using Web API, not sure.
You more likely will have to call the right function from the client who is intimate with the JSON being sent in the request like so: Test1(ListData1 aa), Test2(ListData2 aa)
using the code like below to assist you:
[Serializable]
[DataContract]
public class ListData1
{
[DataMember]
public string r0 { get; set; }
[DataMember]
public string r1 { get; set; }
[DataMember]
public string r2 { get; set; }
[DataMember]
public List<Data1> optdata { get; set; }
public ListData1() { }
public string ToJson()
{
return JSONHelper.Serialize<ListData1>(this);
}
}
[Serializable]
[DataContract]
public class Data1
{
[DataMember]
public string label { get; set; }
[DataMember]
public string d0 { get; set; }
[DataMember]
public string d1 { get; set; }
public Data1() { }
public string ToJSON()
{
return JSONHelper.Serialize<Data1>(this);
}
}
[Serializable]
[DataContract]
public class ListData2
{
[DataMember]
public string r0 { get; set; }
[DataMember]
public string r1 { get; set; }
[DataMember]
public string r2 { get; set; }
[DataMember]
public List<Data2> optdata { get; set; }
public ListData2() { }
public string ToJson()
{
return JSONHelper.Serialize<ListData2>(this);
}
}
[Serializable]
[DataContract]
public class Data2
{
[DataMember]
public string label { get; set; }
[DataMember]
public string d0 { get; set; }
[DataMember]
public string d1 { get; set; }
[DataMember]
public string d2 { get; set; }
public Data2() { }
public string ToJSON()
{
return JSONHelper.Serialize<Data2>(this);
}
}
public static class JSONHelper
{
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
if (string.IsNullOrEmpty(json))
{
return default(T);
}
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
}