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

前端 未结 6 1447
孤街浪徒
孤街浪徒 2020-11-28 18:43

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

properties[\"Value\"] {[
  {
    \"Name\": \"Username\",
    \"Selected\":         


        
相关标签:
6条回答
  • 2020-11-28 18:53

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

    Documentation: Convert JSON to a Type

    0 讨论(0)
  • 2020-11-28 18:57

    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());             
                }                         
    
    0 讨论(0)
  • 2020-11-28 19:00

    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();
    
    0 讨论(0)
  • 2020-11-28 19:04

    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

    0 讨论(0)
  • 2020-11-28 19:12

    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": "sebichondo@gmail.com",
          "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);
            }
    
    0 讨论(0)
  • 2020-11-28 19:13
    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题