[英]Parse JSON to C# object using NewtonSoft JSON.net
I am trying to deserialize a JSON response I get from a webservice. 我正在尝试反序列化从Web服务获得的JSON响应。 I am trying to use NewtonSoft Json.NET. 我正在尝试使用NewtonSoft Json.NET。
I am trying this to parse the response 我正在尝试解析响应
var results = JArray.Parse(response.Content);
I get following exception 我收到以下异常
Newtonsoft.Json.JsonReaderException occurred HResult=0x80131500 发生Newtonsoft.Json.JsonReaderException HResult = 0x80131500
Message=Error reading JArray from JsonReader. Message =从JsonReader读取JArray时出错。 Current JsonReader item is not an array: StartObject. 当前JsonReader项不是数组:StartObject。 Path '', line 1, position 1. 路径'',第1行,位置1。
Source=Newtonsoft.Json 来源= Newtonsoft.Json
I probably need to define the object to return but am not sure how to specify following response (sorry about the formatting, the indentions was removed by the editor here): 我可能需要定义要返回的对象,但不确定如何指定以下响应(对格式感到抱歉,缩进已在此处被编辑器删除):
{"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"
}
]}
Define a class and deserialize it: 定义一个类并反序列化它:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.