Restsharp从内容

时间:2017-11-03 14:41:40

标签: c# json restsharp

我试图从我的内容中获取特定值,但我不知道我该怎么做。

我使用RestSharp(C#)来运行我的JSON代码,但是当我执行命令时它会返回错误。我需要从属性 errorMessage 中获取值。

var json = JsonConvert.SerializeObject(objectToUpdate);
var request = new RestRequest(Method.POST);

request.RequestFormat = DataFormat.Json;
request.AddCookie("authToken", token);
request.AddParameter("application/json", json, ParameterType.RequestBody);

var response = client.Execute<T>(request);

After execute this code my response return the below JSON:

{
    "response":{},
    "status":{
        "success":false,
        "detail":{
            "errormessage":[{
                "fieldName":"departmentCode",
                "errorMessage":"Department code provided is already associated with another department",
                "errorCode":"DUPLICATE_DEPARTMENT_CODE"
            }],
            "error":"Validation failure on request",
            "operation":"internal",
            "errorcode":"412"
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以拥有一个代表您期望的响应的类:

class ApiResponse{
    // use a class that represents normal response instead of object
    // if you need to interact with it.
    public object Response {get; set;}
    public ResponseStatus Status{get; set;}
}
class ResponseStatus {
    public StatusDetail Detail{get; set;}
    public bool Success {get; set;}
}
class StatusDetail {
    public ErrorMessage[] ErrorMessage{get; set;}
}
class ErrorMessage{
    public string FieldName{get; set;}
    public string ErrorMessage{get; set;}
    public string ErrorCode{get; set;}
}

然后你就可以从RestSharp客户端获得解析的响应:

var response = client.Execute<ApiResponse>(request);
var message = response.Data.Response.Detail.ErrorMessage.First().ErrorMessage;

根据RestSharp文档,他们建议使用响应类而不是动态对象(https://github.com/restsharp/RestSharp/wiki/Recommended-Usage)。