繁体   English   中英

使用NewtonSoft JSON.net将JSON解析为C#对象

[英]Parse JSON to C# object using NewtonSoft JSON.net

我正在尝试反序列化从Web服务获得的JSON响应。 我正在尝试使用NewtonSoft Json.NET。

我正在尝试解析响应

var results = JArray.Parse(response.Content);

我收到以下异常

发生Newtonsoft.Json.JsonReaderException HResult = 0x80131500
Message =从JsonReader读取JArray时出错。 当前JsonReader项不是数组:StartObject。 路径'',第1行,位置1。
来源= 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"
   }

]}

在解析json对象时,应使用

var results = JObject.Parse(response.Content);

JArray.Parse用于数组为

 ['Small', { 'oneProp': 'Medium' }, 'Large' ]

您可以在此处查看文档。

定义一个类并反序列化它:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM