0

我正在调用 Json 网络服务并关注 Json

{
    "Content": {
        "CallId": "345353-981b-41a8-a108-a5d6891a7987",
        "Detail": {
            "ConversationId": "345353-981b-41a8-a108-a5d6891a7987",
            "UserId": "d232ad07-3fb6-4ecd-85f7-1c41a8c43013",
            "Region": "beta.us",
            "GroupId": "CT-VIP",
            "WalletId": "d232ad07-3fb6-4ecd-85f7-1c41a8c43013",
            "TrunkId": "d232ad07-3fb6-4ecd-85f7-1c41a8c43013"
        },
        "CallService": {
            "Region": "beta.us",
            "Id": "764bac3af1d84c7db8fe49b2f76e64c0"
        }
    },
    "Status": "OK"
}

我正在使用以下代码发出请求并获得响应:

public string MakeCallTrucnkCall(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers.Add("X-Client:" + "dfsdfs; dsfsdfsf; 151.1.1; 1");
        request.Headers.Add("X-Authenticator-Session:" + "code here");

        try
        {
            WebResponse response = request.GetResponse();

            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                return reader.ReadToEnd();                 
            }
        }
        catch (WebException ex)
        {
            WebResponse errorResponse = ex.Response;
            using (Stream responseStream = errorResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                String errorText = reader.ReadToEnd();

                // log errorText
            }
            throw;
        }
    }

如果出现错误,我会收到以下回复:

{
    "Status": "ERR",
    "Errors": [
        {
            "Code": "Err_Auth_NoInfo"
        }
    ]
}

这将返回我使用 reader.ReadToEnd 将其转换为字符串的响应。但我想将此响应转换为我的自定义对象。我在某处读到我可以使用 Javascript 序列化程序类,但是我的类应该由这个 json 填充哪些属性?

我需要像下面这样上课吗?

public class APIResponse{
public Content {get;set;}
public CallId {get;set;}
public ConversationId {get;set;}
public Detail {get;set;}
public UserId {get;set;}
public Region{get;set;}
}

还是会有所不同?我不确定 json 如何映射到自定义对象以及我应该拥有哪些属性以及如何在我的自定义对象而不是字符串上以表单形式获得响应。请建议。

4

1 回答 1

1

您的 C# 类应该看起来像您的 JSON 数据:

public class APIResponse
{
    public APIContent Content { get; set; }
    public string Status { get; set; }
}

public class APIContent
{
    public string CallID { get; set; }
    public APIDetail Detail { get; set; }
    public APICallService CallService { get; set; }
}

...

然后你可以反序列化:

JavaScriptSerializer serializer = new JavaScriptSerializer();
APIResponse response = serializer.Deserialize<APIResponse>(request);
于 2013-03-12T12:51:12.303 回答