My json string including a fixed type header and non-fixed type body as bellow:
[DataContract]
public class ServiceResponseHeader
{
[DataMember]
public string ErrorCode { get; set; }
[DataMember]
public string Message { get; set; }
}
[DataContract]
public class ServiceResponse
{
[DataMember]
public ServiceResponseHeader Header { get; set; }
[DataMember]
public object Body { get; set; }
}
At runtime, I can get the type of Body from configuration file, but how can I desterilize the json to the object specified type through DataContractJsonSerializer.ReadObject() ?
The sample code:
string json = @"{ "Header": {"ErrorCode":"0000", "Message":"Got Profile Successfully"}, "Body": [{"DisplayName":"Mike Code","PictureUrl":null,"Title":"Manager"}] }"
Type objType = Type.GetType("MyAssembly.MyTypeName"); //Get Type from configuration file
ServiceResponse obj = new ServiceResponse ()
{
Header = new ServiceResponseHeader(),
Body = Activator.CreateInstance(objType)
};
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
ServiceResponse returnObj = (ServiceResponse)serializer.ReadObject(ms);
}
Here I can get Header(returnObj.Header.Message) properly, but returnObj.Body is not the type of MyAssembly.MyTypeName and I cannot get it's properties.
Any suggestions for solving such issue?