Convert Newtonsoft.Json.Linq.JArray to a list of specific object type
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
Related videos on Youtube

Mdb
Updated on July 17, 2022Comments
-
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>
whereSelectableEnumItem
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 almost 6 yearsBe sure your class definition includes a parameterless constructor.
-
Ensar Turkoglu over 5 yearsSo 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 about 5 yearsSir 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 almost 5 years@nsarchar Have you checked that your property is nullable?
-
user1789573 over 4 yearsYou 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 almost 4 yearsYou 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); }
-
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 yearsThanks this worked for me using dynamic objects in C#
-
Chad Hedgcock almost 3 yearsYou'll also see this error If you accidentally use the non-generic
JsonConvert.DeserializeObject(value)
instead ofJsonConvert.DeserializeObject<T>(value)
-
Weslley Rufino de Lima over 1 yearI'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 9 monthsWesslley - convert your object to Newtonsoft.Json.Linq.JArray first and then call .ToObject<... on that