Error Converting a JSON-type string to Class in C #

0

I am building a Web Api in c # Where in one of the operations I return a string that serialized

like this:

 public string  GetCliente()
        {
            string resultado = string.Empty;
            DataTable dt = new DataTable();
            dt = Engine.FuncionesDb.TableDataCliente();
            List<Cliente> Customer = new List<Cliente>();
            if (dt.Rows.Count == 0)
            {
                return resultado;
            }
            else
            {
             Customer = SetListaCliente(dt);
             resultado = JsonConvert.SerializeObject(Customer);
            }

            return resultado;
        }

This method converts the DataTable into a List

  private List<Cliente> SetListaCliente (DataTable dt)
    {
        List<Cliente> Customer = new List<Cliente>();
        foreach (DataRow r in dt.Rows)
        {
            Cliente lineaCliente = new Cliente
            {
                Numero = Convert.ToInt32(r[0]),
                Id = r[1].ToString(),
                Nombre = r[2].ToString(),
                Edad = Convert.ToInt32(r[3]),
                Telefono = r[4].ToString(),
                Mail = r[5].ToString(),
                Saldo = Convert.ToDouble(r[6]),
                FechaCreacion = Convert.ToDateTime(r[7]),
                FechaCreacionUtc = Convert.ToDateTime(r[8]),
                FechaModificacion = Convert.ToDateTime(r[9]),
                FechaModificacionUtc = Convert.ToDateTime(r[10]),
                Proceso = Convert.ToInt32(r[11]),
                Usuario = r[12].ToString(),
                Estado = r[13].ToString(),
            };
            Customer.Add(lineaCliente);
        }
        return Customer;
    } 

my client class

public class Cliente
    {
        public int Numero { get; set; }

        public string  Id { get; set; }

        public string Nombre { get; set; }

        public int Edad { get; set; }

        public string Telefono { get; set; }

        public string Mail { get; set; }

        public double  Saldo  { get; set; }

        public DateTime FechaCreacion { get; set; }

        public DateTime FechaCreacionUtc { get; set; }

        public DateTime FechaModificacion { get; set; }

        public DateTime FechaModificacionUtc { get; set; }

        public int Proceso { get; set; }

        public string Usuario { get; set; }

        public string Estado { get; set; }
    }

How can I make a client list again in my client application? I have done it in several ways and it always returns error.

I should not give an error

resultado = response.Content.ReadAsStringAsync().Result;
                List<Cliente> Customer = new JavaScriptSerializer().Deserialize<List<Cliente>>(resultado);
    
asked by Efrain Mejias C 07.08.2018 в 02:18
source

2 answers

1

You are serializing the Datatable well, but your problem is to understand what happens when you serialize the Datatable

string jsonCliente = JsonConvert.SerializeObject(dt);

In this case, serializing a table (containing a list of rows) generates a JSON with an array of objects with the properties of the table, example

[
  { columna1: 1, columna2: 2, columna3: 3},
  { columna1: 11, columna2: 12, columna3: 13 }
   /* ... */
]

Maybe in your case when searching by the id, you will get an empty array or with a single object

For this reason, your code has an error when trying to deserialize a list in a Client object

jsonCliente = JsonConvert.DeserializeObject<Cliente> // ERROR con la estrutura

Instead you have to Deserialize to a list in this case List

jsonCliente = JsonConvert.DeserializeObject<List<Cliente>> // Serializacion de una lista

After this you can use jsonCliente.FirstOrDefault () for the object or do what you require with the list.

    
answered by 07.08.2018 в 03:45
0

answer based on:

enter the description of the link here

The error was found when deserializar the dates

1 Modify my class

    public class Cliente
    {

            [JsonProperty("Numero")]
            public int Numero { get; set; }

            [JsonProperty("Id")]
            public string Id { get; set; }

            [JsonProperty("Nombre")]
            public string Nombre { get; set; }

            [JsonProperty("Edad")]
            public int Edad { get; set; }

            [JsonProperty("Telefono")]
            public string Telefono { get; set; }

            [JsonProperty("Mail")]
            public string Mail { get; set; }

            [JsonProperty("Saldo")]
            public double Saldo { get; set; }

            [JsonConverter(typeof(CustomDateTimeConverter))]
            public DateTime FechaCreacion { get; set; }

            [JsonConverter(typeof(CustomDateTimeConverter))]
            public DateTime FechaCreacionUtc { get; set; }

            [JsonConverter(typeof(CustomDateTimeConverter))]
            public DateTime FechaModificacion { get; set; }

            [JsonConverter(typeof(CustomDateTimeConverter))]
            public DateTime FechaModificacionUtc { get; set; }

            [JsonProperty("Proceso")]
            public int Proceso { get; set; }

            [JsonProperty("Usuario")]
            public string Usuario { get; set; }

            [JsonProperty("Estado")]
            public string Estado { get; set; }

            [JsonProperty("Transaccion")]
            public string Transaccion { get; set; }
}

2 Add this new class to my code

 public class CustomDateTimeConverter : DateTimeConverterBase
        {
            /// <summary>
            /// DateTime format
            /// </summary>
            private const string Format = "dd. MM. yyyy HH:mm";

            /// <summary>
            /// Writes value to JSON
            /// </summary>
            /// <param name="writer">JSON writer</param>
            /// <param name="value">Value to be written</param>
            /// <param name="serializer">JSON serializer</param>
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                writer.WriteValue(((DateTime)value).ToString(Format));
            }

            /// <summary>
            /// Reads value from JSON
            /// </summary>
            /// <param name="reader">JSON reader</param>
            /// <param name="objectType">Target type</param>
            /// <param name="existingValue">Existing value</param>
            /// <param name="serializer">JSON serialized</param>
            /// <returns>Deserialized DateTime</returns>
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                if (reader.Value == null)
                {
                    return null;
                }

                var s = reader.Value.ToString();
                DateTime result;
                if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                {
                    return result;
                }

                return DateTime.Now;
            }
        }

3 My code

 private string  ClientGetRequest(string RequestURI)
        {
            string resultado = string.Empty;

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:50445/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = new HttpResponseMessage();
            response = client.GetAsync(RequestURI).Result;
            if (response.IsSuccessStatusCode)
            {
                resultado = response.Content.ReadAsStringAsync().Result;
                resultado = resultado.Replace("\", "");
                resultado = resultado.Replace("/", "");
                resultado = resultado.Replace("\"[", "[");
                resultado = resultado.Replace("]\"", "]");
                string [] partes = resultado.Split(',');


                var resulta = resultado;
                List<Cliente> json = JsonConvert.DeserializeObject<List<Cliente>>(resulta);

            }
            else
            {
                resultado  = response.IsSuccessStatusCode.ToString();
            }

            return resultado;
        }
    
answered by 14.08.2018 в 19:43