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

本文关键字:动态 对象 反序列化 json 结果 | 更新日期: 2023-09-27 18:04:30

我想反序列化从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; }
}

当调用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; }
}

下面是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;
    }

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

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

您可以使用以下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; }
}

如果你给你的数据字段一个类型,序列化器将能够解析它并创建适当的对象。您也不再需要将Data字段强制转换为您想要的值。

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。数据和数据2。