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

Deserialize json result to dynamic object

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

我的意思是我的 ApiResponse class 是:

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

当 API 的 Method1 被调用时。 Data 将是 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; }
}

这是方法 1 和方法 2 调用的 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;
    }

我想根据方法调用反序列化数据对象。你能帮我做吗?

您可以使用以下 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 现在属于正确的类型。