将json结果反序列化为动态对象

时间:2015-07-24 07:34:31

标签: c# json json-deserialization javascriptserializer

我想反序列化从API调用返回的json结果。对于不同的API方法调用,数据将位于不同的类对象中。

我的意思是我的ApiResponse课程是:

public class ApiResponse
{
    public object Data { get; set; }
    public string ResultCode { get; set; }
    public string ResultMessage { get; set; }
    public string Exception { get; set; }
}

调用Method1 for API时。数据将是Method1Result对象,当调用Method2时Data将是一个Method2Result对象

public class Method1Result
{
    public int property1 { get; set; }
    public string property2 { get; set; }
}

public class Method2Result
{
    public string property3 { get; set; }
    public decimal property4 { get; set; }
}

以下是Method1和Method2调用的json结果:

{"Data": { “property1” : 1, “property2” : "test" }
,"ResultCode":"Success","ResultMessage":"","Exception":null}

{"Data": { “property3” : "ok", “property4” : 10 }
,"ResultCode":"Success","ResultMessage":"","Exception":null}

这些

有两种方法
private ApiResponse Method1Call(ApiRequest request)
    {
        JavaScriptSerializer serializer1 = new JavaScriptSerializer();

        string serviceAddress = "/Method1";
        var pResponseJson = HttpCall(serializer1.Serialize(request),serviceAddress);

        ApiResponse response = serializer1.Deserialize<ApiResponse>(pResponseJson);

        // I WANT TO GET PROPERTY OF property1 and property2 here
        int temp = ((Method1Result)response.Data).property1;
        return apiResponse;
    }

 private ApiResponse Method2Call(ApiRequest request)
    {
        JavaScriptSerializer serializer1 = new JavaScriptSerializer();

        string serviceAddress = "/Method2";
        var pResponseJson = HttpCall(serializer1.Serialize(request),serviceAddress);

        ApiResponse response = serializer1.Deserialize<ApiResponse>(pResponseJson);

        // I WANT TO GET PROPERTY OF property3 and property4 here
        string temp = ((Method2Result)response.Data).property3;
        return apiResponse;
    }

我想基于方法调用反序列化Data对象。你能帮帮我吗?

1 个答案:

答案 0 :(得分:3)

您可以使用以下ApiResponse对象定义:

public class ApiResponse<T>
{
    public T Data { get; set; }
    public string ResultCode { get; set; }
    public string ResultMessage { get; set; }
    public string Exception { get; set; }
}

如果为数据字段指定类型,则序列化程序将能够解析它并创建适当的对象。您也不再需要将数据字段转换为您想要的内容。

var response1 = @"{""Data"": { ""property1"" : 1, ""property2"" : ""test"" }, ""ResultCode"":""Success"",""ResultMessage"":"""",""Exception"":null}";
var response2 = @"{""Data"": { ""property3"" : ""ok"", ""property4"" : 10 }, ""ResultCode"":""Success"",""ResultMessage"":"""",""Exception"":null}";

var serializer  = new JavaScriptSerializer();
var data1       = serializer.Deserialize<ApiResponse<Method1Result>>(response1);
var data2       = serializer.Deserialize<ApiResponse<Method2Result>>(response2);

data1.Data和data2.Data现在属于正确的类型。