【问题标题】:How to set status to Json array .net?如何将状态设置为 Json 数组 .net?
【发布时间】:2017-11-17 07:46:37
【问题描述】:

我有一个以字符串格式返回 json 数组 (JArray) 的 Web 服务,但我不明白如何将状态值添加到该操作并在使用该服务的应用程序中获取它。

我的问题是,我应该在 json 数组中返回一个带有消息的 json 对象吗?还是只是一个数组?哪个更方便?

我的生活:

    public string getList(string strSalary)
    {
        List<Employee> listJson = null;
        JObject jsonResp = "";
        JArray array = null;

        try
        {
            listJson = ReportBLL.getInstance.listEmployees(int.Parse(strSalary));
            array = JArray.FromObject(listJson);

            //set array status ?: ej
            //array status = "succes";
        }
        catch (Exception ex)
        {
           //set error message
           // array status = "error";
           //array message = ex.Message or "Not found employees";
        }

        return JsonConvert.SerializeObject(array);
    }

客户端调用(其他 asp 应用):

 public static List<Employee> listEmployeeClient(string salary)
 {
   JObject jo = null;  //or arrayjson ?
   string strData = "";

   strData = webService.getList(salary);
   jo = JObject.Parse(strData);

 //how to evalue status request ?
 /* example
      if(jo.status == "error") {
          throw new Exception(jo.message);
      } else {
          iterate array inside json object ?
      }
 */
}

这个逻辑正确吗?

【问题讨论】:

    标签: c# .net json return response


    【解决方案1】:

    您可以为 API Response 创建一个新实体并将其用于所有 API 响应,您可以通过以下示例对其进行测试。

    在服务器中:

        Class APIResponse<T> 
        {        
            public bool IsError;
    
            public int ErrorCode;
    
            public string ErrorMessage;
    
            public T ReponseData; 
        }
    
        public string getList(string strSalary)
        {
    
        List<Employee> listJson = null;
        APIResponse<Employee> responseString = new  APIResponse<Employee>();
    
        try
        {
            listJson = ReportBLL.getInstance.listEmployees(int.Parse(strSalary));
            responseString.isError = false;
            responseString.data = JArray.FromObject(listJson);
    
        }
        catch (Exception ex)
        {
         responseString.IsError = true;
         responseString.ErrorCode = 404; //You can add custom error codes
         responseString.ErrorMessage = ex;
        }
        return JsonConvert.SerializeObject(responseString);
        }
    

    在客户端:

     public static List<Employee> listEmployeeClient(APIResponse<Employee> salary)
     {
         //You can access the  model here
     }
    

    【讨论】:

      【解决方案2】:

      有很多选择。如果您有 REST api,您可以为每个请求使用 HTTPStatusCodes,例如200 表示 OK,400 表示错误请求等。

      如果您想要更精细的调整,您可以拥有响应对象的一般结构,例如

      responseDto:
           status:  any code, error or success
           message: any error message
           data:    any expected data
      

      【讨论】:

        【解决方案3】:

        serializing之前使用Dictionary&lt;string,object&gt;,在deserializing之后使用dynamic方便获取各个字段。 jArray.ToObject&lt;List&lt;Employee&gt;&gt;() 会将 JArray 对象转换回正确的类型。

        下面的例子:

        class Employee
        {
           public string Name { get; set; }
        }
        
        // serializing
        var employees = new List<Employee>()
        {
          new Employee() {Name = "john"},
          new Employee() {Name = "alex"},
          new Employee() {Name = "susan"},
          new Employee() {Name = "bryan"},
        };
        
        var dict = new Dictionary<string, object>
        {
          ["employees"] = employees,
          ["status"] = "error",
          ["errormessage"] = "Not found employees"
        };
        var json = JsonConvert.SerializeObject(dict);
        
        // deserializing 
        dynamic deserialized = JsonConvert.DeserializeObject(json);
        string status = deserialized.status;
        string errorMessage = deserialized.errormessage;
        
        JArray jArray = deserialized.employees;
        List<Employee> deserializedEmployee = jArray.ToObject<List<Employee>>();
        

        【讨论】:

          猜你喜欢
          • 2017-08-17
          • 2017-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-14
          • 2020-09-10
          • 1970-01-01
          • 2018-10-21
          相关资源
          最近更新 更多