我正在尝试反序列化从网络服务获得的 JSON 响应。我正在尝试使用 NewtonSoft Json.NET。
我正在尝试解析响应
var results = JArray.Parse(response.Content);
我收到以下异常
Newtonsoft.Json.JsonReaderException occurred HResult=0x80131500
Message=Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.
Source=Newtonsoft.Json
我可能需要定义要返回的对象,但不确定如何指定以下响应(对于格式,缩进已被编辑器删除):
{"result": [
{
"recordType": "sys_ui_script",
"hits": [],
"tableLabel": "UI Script"
},
{
"recordType": "sys_script",
"hits": [
{
"name": "Approval Events (Non-Task)",
"className": "sys_script",
"tableLabel": "sys_script",
"matches": [ {
"field": "script",
"fieldLabel": "Script",
"lineMatches": [
{
"line": 21,
"context": " updateRecord(current, current.approver.getDisplayValue() + \" rejected the task.\", ",
"escaped": " updateRecord(current, current.approver.getDisplayValue() + " rejected the task.", "
}
],
"count": 2
}],
"sysId": "ad15c8149f4010008f88ed93ee4bcc9f",
"modified": 1489179469000
}
],
"tableLabel": "Business Rule"
}
]}
最佳答案
定义一个类并反序列化它:
var results = JsonConvert.DeserializeObject<RootObject>(response.Content);
public class LineMatch
{
public int line { get; set; }
public string context { get; set; }
public string escaped { get; set; }
}
public class Match
{
public string field { get; set; }
public string fieldLabel { get; set; }
public List<LineMatch> lineMatches { get; set; }
public int count { get; set; }
}
public class Hit
{
public string name { get; set; }
public string className { get; set; }
public string tableLabel { get; set; }
public List<Match> matches { get; set; }
public string sysId { get; set; }
public long modified { get; set; }
}
public class Result
{
public string recordType { get; set; }
public List<Hit> hits { get; set; }
public string tableLabel { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
}
关于c# - 使用 NewtonSoft JSON.net 将 JSON 解析为 C# 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46326395/