Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

304,376

Solution 1

Just call array.ToObject<List<SelectableEnumItem>>() method. It will return what you need.

Documentation: Convert JSON to a Type

Solution 2

The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark" and the property in code is FirstName then use the Select method as follows

List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
    FirstName = (string)x["first_name"],
    Selected = (bool)x["selected"]
}).ToList();

Solution 3

The API return value in my case as shown here:

{
  "pageIndex": 1,
  "pageSize": 10,
  "totalCount": 1,
  "totalPageCount": 1,
  "items": [
    {
      "firstName": "Stephen",
      "otherNames": "Ebichondo",
      "phoneNumber": "+254721250736",
      "gender": 0,
      "clientStatus": 0,
      "dateOfBirth": "1979-08-16T00:00:00",
      "nationalID": "21734397",
      "emailAddress": "[email protected]",
      "id": 1,
      "addedDate": "2018-02-02T00:00:00",
      "modifiedDate": "2018-02-02T00:00:00"
    }
  ],
  "hasPreviousPage": false,
  "hasNextPage": false
}

The conversion of the items array to list of clients was handled as shown here:

 if (responseMessage.IsSuccessStatusCode)
        {
            var responseData = responseMessage.Content.ReadAsStringAsync().Result;
            JObject result = JObject.Parse(responseData);
            var clientarray = result["items"].Value<JArray>();
            List<Client> clients = clientarray.ToObject<List<Client>>();
            return View(clients);
        }

Solution 4

using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

Solution 5

I can think of different method to achieve the same

IList<SelectableEnumItem> result= array;

or (i had some situation that this one didn't work well)

var result = (List<SelectableEnumItem>) array;

or use linq extension

var result = array.CastTo<List<SelectableEnumItem>>();

or

var result= array.Select(x=> x).ToArray<SelectableEnumItem>();

or more explictly

var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });

please pay attention in above solution I used dynamic Object

I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.

Myself I use the first one

Share:
304,376

Related videos on Youtube

Mdb
Author by

Mdb

Updated on July 17, 2022

Comments

  • Mdb
    Mdb 5 months

    I have the following variable of type {Newtonsoft.Json.Linq.JArray}.

    properties["Value"] {[
      {
        "Name": "Username",
        "Selected": true
      },
      {
        "Name": "Password",
        "Selected": true
      }
    ]}
    

    What I want to accomplish is to convert this to List<SelectableEnumItem> where SelectableEnumItem is the following type:

    public class SelectableEnumItem
        {
            public string Name { get; set; }
            public bool Selected { get; set; }
        }
    

    I am rather new to programming and I am not sure whether this is possible. Any help with working example will be greatly appreciated.

  • Faust
    Faust almost 6 years
    Be sure your class definition includes a parameterless constructor.
  • Ensar Turkoglu over 5 years
    So how to handle if the array has a null field? This time i get the error JsonSerializationException. I want the data and i want it remain null for any null data.
  • Mustafa Demir
    Mustafa Demir about 5 years
    Sir this code getting the first value from my response but I have lots of values how can I get all values.But I need to get just one value I mean there is a firstname and lastname in response.I wanna get just firstname how can i do that ?
  • Jannik
    Jannik almost 5 years
    @nsarchar Have you checked that your property is nullable?
  • user1789573 over 4 years
    You did not use any dynamic Objects. You only used strongly-typed object. Please, look into CLR and DLR for the differences between the two.
  • Mohammed Hossen
    Mohammed Hossen almost 4 years
    You can also use JsonProperty annotation and deserialize your JSON object to a list. public class SelectableEnumItem { [JsonProperty("Name")] public string Name { get; set; } [JsonProperty("Selected")] public bool Selected { get; set; } } public IList<SelectableEnumItem> GetListOfObject(string jsonTextHere) { return JsonConvert.DeserializeObject<List<SelectableEnumItem>>(json‌​TextHere); }
  • VSO
    VSO over 3 years
    @realPro Just worked for me. Are you sure you have an array and that the JObjects in that JArray can map properly?
  • Anthony McGrath over 3 years
    Thanks this worked for me using dynamic objects in C#
  • Chad Hedgcock
    Chad Hedgcock almost 3 years
    You'll also see this error If you accidentally use the non-generic JsonConvert.DeserializeObject(value) instead of JsonConvert.DeserializeObject<T>(value)
  • Weslley Rufino de Lima
    Weslley Rufino de Lima over 1 year
    I'm trying to convert this way, but the messager that appers to me is "object does not contain a definition for 'ToObject' and not acessible extension method 'ToObject' aceppting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)" My variable is declared with type "object" which returns a type "JArray" (Newtonsoft.Json.Linq.JArray). Who can help me?
  • Mike W
    Mike W 9 months
    Wesslley - convert your object to Newtonsoft.Json.Linq.JArray first and then call .ToObject<... on that