簡體   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