c# - 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>
当我收到回复时,我该如何处理所有这些
解决方案
您可以先检查空响应,然后在 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");
}
}
}
推荐阅读
- ios - 为什么 Appstore 一直要求我提供 NSCalendarsUsageDescription,即使我已经在我的 plist 中提供了 NSCalendarsUsageDescription?
- python - TTypeError:(“-:'str'和'float'的不支持的操作数类型”,'发生在索引FFT峰值(Hz)')
- python - 在 cx-Freeze 之后,QPrinter 看不到任何打印机
- mathjax - 在 xaringan 幻灯片中禁用 MathJax 方程参考链接
- html - 是否可以更改博客中的主题结构
- virtual-machine - 我如何使用 libvirt 获得 virtio-serial 的 pts 编号(/dev/pts/[X])?
- r - 在代码块中组合管道函数
- shell - 如何使用 shell 脚本从输出中获取特定值?
- java - 为什么不使用静态 void main 方法,而是使用非静态方法
- python - Python 元编程:使用类型注释生成函数签名