Convertir Newtonsoft.Json.Linq.JArray a una lista de tipo de objeto específico


Tengo la siguiente variable de tipo {Newtonsoft.Json.Linq.JArray}.

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

]}

Lo que quiero lograr es convertir esto a List<SelectableEnumItem> donde SelectableEnumItem es el siguiente tipo:

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

Soy más bien ner a la programación y no estoy seguro de si esto es posible. Cualquier ayuda con el ejemplo de trabajo será muy apreciada.

 168
Author: Mdb, 2012-11-26

5 answers

Simplemente llame al método array.ToObject<List<SelectableEnumItem>>(). Te devolverá lo que necesites.

Documentación: Convertir JSON a un Tipo

 346
Author: HoberMellow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-30 20:19:25

El ejemplo de la pregunta es un caso más simple donde los nombres de propiedad coinciden exactamente en json y en código. Si los nombres de las propiedades no coinciden exactamente, por ejemplo, la propiedad en json es "first_name": "Mark" y la propiedad en code es FirstName, use el método Select de la siguiente manera

List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
    FirstName = (string)x["first_name"],
    Selected = (bool)x["selected"]
}).ToList();
 32
Author: Souvik Basu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-23 12:40:55

Puedo pensar en un método diferente para lograr lo mismo

IList<SelectableEnumItem> result= array;

O (tuve alguna situación que este no funcionó bien)

var result = (List<SelectableEnumItem>) array;

O utilice la extensión linq

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

O

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

O más explícitamente

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

Por favor, preste atención en la solución anterior utilicé Objeto dinámico

Puedo pensar en algunas soluciones más que son combinaciones de soluciones anteriores. pero creo que cubre casi todos los métodos disponibles.

Yo mismo uso la primera uno

 2
Author: Mo Hrad A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-27 10:23:53
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
Author: Mohammed Hossen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-26 19:40:34

El valor de retorno de API en mi caso como se muestra aquí:

{
  "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
}

La conversión del array items a la lista de clientes fue manejada como se muestra aquí:

 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
Author: stephen ebichondo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-11 08:37:18