Search code examples
c#jsonjson-deserialization

Parse JSON to C# object using NewtonSoft JSON.net


I am trying to deserialize a JSON response I get from a webservice. I am trying to use 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
Message=Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.
Source=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"
   }

]}

Solution

  • 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; }
    }