How to parse JSON string that can be one of two different strongly typed objects?
- by user852194
Background:
I'm invoking a web service method which returns a JSON string. This string can be of type ASConInfo or ASErrorResponse.
Question:
Using the DataContractJsonSerializer, how can I convert the returned JSON string to one of those objects?
Thanks in advance
I have tried the following technique, but it does not work:
public static object test(string inputString)
{
object obj = null;
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(inputString)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(object));
obj = ser.ReadObject(ms) as object;
}
return obj;
}
[WebMethod]
public string TypeChecker()
{
string str = "{\"Error\":191,\"ID\":\"112345678921212\",\"Length\":15}";
//string strErro = "";
object a = test(str);
if (a is ASResponse)
{
return "ASResponse";
}
if (a is ASErrorResponse)
{
return "ASErrorResponse";
}
return "Nothing";
}