首页 > 解决方案 > c# : 反序列化 json 对象

问题描述

我正在调用一个 api,成功后我将获取 List 格式的 json 数据

[

    {

        "fileName": [
            "file1"
        ],
        "date": [
            "8/25/2015 0:00"
        ],
        "time": [
            "7/16/2009 16:51"
        ],
        "id": "1",
        "version_": 1},
    {

        "fileName": [
            "file1"
        ],
        "date": [
            "8/25/2015 0:00"
        ],
        "time": [
            "7/16/2009 16:51"
        ],
        "id": "1",
        "version_": 1
    }
    ]

出错时,当我传递错误数据时,响应为纯 json 格式

{
   "resultType": "error",
   "errorType": "validationError",
   "errorCode": "validation.error",
   "apiMessage": "Data Validation issue, please correct the data and try again",
   "validationErrors":    [
            {
         "errorCode": "100211",
         "path": "firstName",
         "apiMessage": "Minimum field length not reached"
      },
            {
         "errorCode": "100241",
         "path": "firstName",
         "apiMessage": "Names must have at least one alphabetic character"
      }
   ],
   "requestId": "3f6fb4b5-42a9-44e5-9ed3-6a50c6fdcc52"
}

当没有数据存在时,我得到

<Empty JSON content>

当我收到回复时,我该如何处理所有这些

标签: c#json.netdeserialization

解决方案


您可以先检查空响应,然后在 try-catch 中尝试解析数组。如果它不是数组,它会抛出你可以捕获的异常,并解析 Json 对象:

string resp; //this is where you will store your response from server
JArray array;
JObject json;
if(resp == "<Empty JSON content>")
{
   Console.WriteLine("Response is empty json");
}
else
{
   try
  {
    array = JArray.Parse(resp);
    Console.WriteLine("Array parsed");
  }
  catch (Newtonsoft.Json.JsonException ex)
  {
      try
      {
         json = JObject.Parse(resp);
         Console.WriteLine("error parsed");
      }
      catch(Newtonsoft.Json.JsonException ex2)
      {
         Console.WriteLine("Response was not json object");
      }        
  }
}

推荐阅读