skip to Main Content

I’m getting back the following string from an API call:

{
  "result":
  [
    {
     "sys_id":"12d199028752a9108ae38516dabb35d3"
    }
  ]
}

I’m trying to deserialize it into this class"

  public class result
    {
        public string sys_id { get; set; }
    }

I’m using this call: var x = Newtonsoft.Json.JsonConvert.DeserializeObject<result>(jsonString);

But "x.sys_id" is always coming up as NULL. What am I missing?

3

Answers


  1. Your JSON models an object containing a result property containing an array with an object with a sys_id property, itself a string. However, your result class is for that final object, the one with sys_id. You’re therefore missing a level: you need something to contain those results.

    So let’s define a new class:

    public class Document // or whatever other name you want
    {
        public List<result> result { get; set; }
    }
    

    And then you can deserialize it:

    var x = JsonConvert.DeserializeObject<Document>(jsonString);
    
    Login or Signup to reply.
  2. The structure of the JSON response consists of an object which has a property result of type array, within which you have an object containing a single property sys_id of type string.

    As such, you would need the response to be mapped to something like the following:

    public class Root // change name as necessary
    {
        [JsonProperty("result")]
        public ICollection<ResultItem> Result { get; set; }
    }
    
    public class ResultItem // change name as necessary
    {
        [JsonProperty("sys_id")]
        public string SysId { get; set; }
    }
    

    You would then use it as:

    var x = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(jsonString);
    
    Login or Signup to reply.
  3. sys_id is a string property of an object that is inside of an array, and so the object can be accessed by index only. But you don’t need any classes to obtain it.You can just parse a json string

    string sys_id = (string) JObject.Parse(json)["result"][0]["sys_id"];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search