JSON 值可能为空

本文关键字:JSON | 更新日期: 2023-09-27 18:18:08

所以...我从这里得到了"Parse"类,如果所有值都从 JSON 字符串正确返回,但它工作正常,但如果在我的情况下,某些 JSON 值不可用(它们根本不存在,"项目"和"current_time"不存在。 程序当然会崩溃。

我的问题是,我该如何应对?我已经尝试将 JSON 值存储到变量中,但这也会使程序崩溃,但没有提供更多信息。

工作:

{
    "response": {
        "success": 1,
        "current_time": 1445015502,
        "items": {
            "item1": {
                "property1": 1,
                "property2": "test",
                "property3": 4.3
            },
            "item2": {
                "property1": 5,
                "property2": "test2",
                "property3": 7.8
            }
        }
    }
}

崩溃:

{
    "response": {
        "success": 0,
        "message": "not available",
    }
}

JSON 值可能为空

答案将在这里:

private RootObject Parse(string jsonString)
{
   dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
   RootObject parsed = new RootObject()
   {
        response = new Response()
        {
              success = jsonObject.response.success,
              current_time = jsonObject.response.current_time,
              message = jsonObject.response.message,
              items = ParseItems(jsonObject.response.items)
        }  
   };
   return parsed;
}

在解析对象之前,您需要确定它是否是有效(成功(的对象,因此您需要执行以下操作:

private RootObject Parse(string jsonString)
{
   dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
   if (jsonObject.response.success == 0)
   {
      //The response object is not valid and has a message...
      throw new InvalidArgumentException("I don't know what to do");
   }
   else
   {
      RootObject parsed = new RootObject()
      {
           response = new Response()
           {
              success = jsonObject.response.success,
              current_time = jsonObject.response.current_time,
              message = jsonObject.response.message,
              items = ParseItems(jsonObject.response.items)
           }  
      };
      return parsed;
   }
}

或者你可以做:

private RootObject Parse(string jsonString)
{
   dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
   RootObject parsed = null;
   if (jsonObject.response.success == 0)
   {
      //The response object is not valid and has a message...
      parsed = new RootObject()
      {
           response = new Response()
           {
              success = jsonObject.response.success,
              message = jsonObject.response.message
           } 
      };
   }
   else
   {
      parsed = new RootObject()
      {
           response = new Response()
           {
              success = jsonObject.response.success,
              current_time = jsonObject.response.current_time,
              message = jsonObject.response.message,
              items = ParseItems(jsonObject.response.items)
           }  
      };
   }
   return parsed;
}
在使用

"items"字段之前,您必须验证它是否为空。

如果您已经这样做了,我认为我们将需要更多信息。