如何将状态设置为 Json array .net?

How to set status to Json array .net?

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

我的问题是,我应该 return 一个带有消息并位于 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 ?
      }
 */
}

这个逻辑对吗?

serializing之前使用一个Dictionary<string,object>,在deserializing之后使用dynamic方便获取各个字段。 jArray.ToObject<List<Employee>>() 会将 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>>();

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

如果你想要更精细的调整,你可以有一个通用的响应对象结构,例如

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

您可以为 API 响应创建一个新实体并将其用于所有 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
 }