【问题标题】:Restsharp getting especific JSON value from contentRestsharp 从内容中获取特定的 JSON 值
【发布时间】:2017-11-03 14:41:39
【问题描述】:

我正在尝试从我的内容中获得特定的价值,但我不知道该怎么做。

我正在使用 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"
        }
    }
}

【问题讨论】:

  • 尝试“request.Parameters.Clear();”在 "request.AddCookie("authToken", token);"之前
  • 可以看看stackoverflow.com/questions/11400879/…。其他 - 错误消息显示您的消息未通过验证 - 您在 departmentCode 中存在内容问题
  • 你好@DarkoMaricProgramer,我的参数没有问题,我只需要从errorMessage获取信息保存在我的日志中。
  • 我明白了...然后尝试:动态结果 = JObject.Parse(response); var detail = result.status.detail.errormessage; foreach(详细的 var 项){};

标签: c# json restsharp


【解决方案1】:

你可以有一个类,代表你期望的响应:

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)。

【讨论】:

  • 谢谢大家。我使用了 Justinas 所说的示例,并且... PUFFF .... 我构建了类的结构并且代码有效.... ApiResponse apiResponse = new ApiResponse(); apiResponse.Response = JsonConvert.DeserializeObject(JObject.Parse(response.Content)["status"].ToString());
猜你喜欢
  • 2022-01-14
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2017-11-30
  • 2019-03-30
  • 2017-11-22
  • 2017-09-19
相关资源
最近更新 更多