Problem deserializar JSON with NewtonSoft.JSON ASP.NET MVC 5

0

I have followed the advice of several questions here in stackoverflow in Spanish and the same in English, I have already lost two days with this and I have not found the problem, I have the following JSON that is valid:

[
  {
    "Info": {
      "Codigo": 400,
      "Nombre": "ABRAZADERA  2\"",
      "Referencia": "2\"",
      "Cantidad": 10,
      "Marca": "GENERICO",
      "Categoria": 14,
      "Costo": 0,
      "Area": 1,
      "Medida": 1,
      "StockMinimo": 50,
      "Estado": 0,
      "StockPedido": 75,
      "StockMaximo": 150
    },
    "Componentes": [
      {
        "Codigo": 399,
        "Nombre": "ABRAZADERA  4\"",
        "Referencia": "4\"",
        "Parent": 400,
        "Cantidad": 2
      },
      {
        "Codigo": 403,
        "Nombre": "ABRAZADERA 1\"",
        "Referencia": "1\"",
        "Parent": 400,
        "Cantidad": 1
      },
      {
        "Codigo": 663,
        "Nombre": "ACEITE /REFRIGERANTE(CAPELA)PAG 100",
        "Referencia": "R-134A",
        "Parent": 400,
        "Cantidad": 0
      }
    ],
    "Garantias": []
  }
]

and I have the following classes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SisVEMweb.ViewModels.JsonModels.AlmacenJson
{
    public class VerPiezaJson
    {
        public class Info
        {
            public int Codigo { get; set; }
            public string Nombre { get; set; }
            public string Referencia { get; set; }
            public int Cantidad { get; set; }
            public string Marca { get; set; }
            public int Categoria { get; set; }
            public int Costo { get; set; }
            public int Area { get; set; }
            public int Medida { get; set; }
            public int StockMinimo { get; set; }
            public int Estado { get; set; }
            public int StockPedido { get; set; }
            public int StockMaximo { get; set; }
        }

        public class Componente
        {
            public int Codigo { get; set; }
            public string Nombre { get; set; }
            public string Referencia { get; set; }
            public int Parent { get; set; }
            public int Cantidad { get; set; }
        }

        public class Garantia
        {
            public int Codigo { get; set; }
            public string Area { get; set; }
            public string Descripcion { get; set; }
            public DateTime FechaInicio { get; set; }
            public DateTime FechaFinal { get; set; }
            public string Tipo { get; set; }
        }

        public class VerPieza
        {
            public Info Info { get; set; }
            public List<Componente> Componentes { get; set; }
            public List<Garantia> Garantias { get; set; }
        }

    }
}

Here I try to deserialize the JSON, it is clear that it does receive the data correctly, except in deserialize:

public async Task<ActionResult> VerPieza(int id)
        {

            var Piezas = new VerPieza();

            using (var aPieza = new HttpClient())
            {
                aPieza.BaseAddress = new Uri(BaseUrl);

                aPieza.DefaultRequestHeaders.Clear();

                aPieza.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage Result = await aPieza.GetAsync("almacen/piezas/ver?id=" + id.ToString());

                if (Result.IsSuccessStatusCode)
                {
                    var Resultado = Result.Content.ReadAsStringAsync().Result;

                    Piezas = JsonConvert.DeserializeObject<VerPieza>(Resultado);
                }
            }

            return View(Piezas);
        }

When executing, it throws this error at me:

  

Can not deserialize the current JSON array (e.g. [1,2,3]) into type   'SisVEMweb.ViewModels.JsonModels.AlmacenJson.VerPiezaJson + VerPieza'   because the type requires a JSON object (e.g. {"name": "value"}) to   deserialize correctly. To fix this error either change the JSON to a   JSON object (e.g. {"name": "value"}) or change the deserialized type to   an array or a type that implements a collection interface (e.g.   ICollection, IList) like List that can be deserialized from to JSON   array JsonArrayAttribute can also be added to the type to force it to   deserialize from to JSON array. Path '', line 1, position 1.

There is a lot on the subject and I have followed each of the examples and I have not been able to come up with this problem.

What am I failing?

Greetings.

Update:

Still trying to serialize with the same classes to see what the resulting json is still I can not serialize either, this is what I did:

    public JsonResult PiezaTest()
    {
        Info info = new Info() {
            Codigo = 400,
            Area = 1,
            Categoria = 1,
            Cantidad = 10,
            Costo = 171.0M,
            Estado = 1,
            Marca = "PRUEBA",
            Medida = 1,
            Nombre = "ABRAZADERA 2\"",
            Referencia = "2\"",
            StockMaximo = 50,
            StockMinimo = 10,
            StockPedido = 25
        };

        List<Componente> compos = new List<Componente>();

        for (var i = 0; i <= 5; i++)
        {
            compos.Add(new Componente()
            {
                Codigo = 380 + i,
                Nombre = "ABRAZADERA " + i.ToString(),
                Referencia = "PRUEBA",
                Parent = 400,
                Cantidad = 2
            });
        }

        var Pieza = new VerPiezaInfo()
        {
            Info = info,
            Componentes = compos,
            Garantias = null
        };

        JsonSerializerSettings config = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            Formatting = Formatting.Indented
        };

        string result = JsonConvert.SerializeObject(Pieza, config);

        return Json(result);
    }

I miss an error:

  

type 'SisVEMweb.ViewModels.JsonModels.AlmacenJson.VerPiezaInfo' to   type 'System.Collections.IEnumerable'. '

However, if I serialize the properties separately from the VerPiezaInfo class, it returns them without problems.

I almost throw the towel with this.

    
asked by Enecumene 26.06.2018 в 20:01
source

0 answers