327

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.

6 Answers 6

670

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

Documentation: Convert JSON to a Type

7
  • 11
    Be sure your class definition includes a parameterless constructor.
    – Faust
    Mar 13, 2017 at 23:34
  • 1
    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. Apr 19, 2017 at 11:09
  • 1
    @nsarchar Have you checked that your property is nullable?
    – Jannik
    Feb 3, 2018 at 10:50
  • @realPro Just worked for me. Are you sure you have an array and that the JObjects in that JArray can map properly?
    – VSO
    Jun 3, 2019 at 14:21
  • 2
    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? Sep 2, 2021 at 9:41
48

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();
1
  • 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 ?
    – tpbafk
    Nov 15, 2017 at 9:12
18

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);
        }
1
  • Thanks this worked for me using dynamic objects in C# Jun 3, 2019 at 18:21
2

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

1
  • 1
    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. Jul 2, 2018 at 19:33
2
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;
  }
}
1
  • 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>>(jsonTextHere); } Jan 9, 2019 at 18:51
1

Use IList to get the JArray Count and Use Loop to Convert into List

       var array = result["items"].Value<JArray>();

        IList collection = (IList)array;

        var list = new List<string>();

        for (int i = 0; i < collection.Count; j++)
            {
              list.Add(collection[i].ToString());             
            }                         

Not the answer you're looking for? Browse other questions tagged or ask your own question.