Error when deserializing JSON string in Object Class?

2

On my server I do this:

 [HttpGet]
        public string GetSeleccionarTodasFilasTabla(string NombreTabla, string Version)
        {
            string resultado = string.Empty;
            Engine.EngineDb FuncionDb = new Engine.EngineDb();          
            int permiso = FuncionDb.PermisoSync(Version);
            if (permiso < 1)
            {
                return resultado = Engine.EngineData.SyncNoPermitida;
            }
            DataTable dt = new DataTable();
            dt = FuncionDb.SeleccionarTodasFilasTabla(NombreTabla);
            if (dt.Rows.Count != 0)
            {
                resultado = JsonConvert.SerializeObject(dt, Formatting.Indented);
            }
            else
            {
                resultado = Engine.EngineData.NoHayFilas;
            }
            return resultado;
        }

Returns a string like this

"[\r\n  {\r\n  \"IdAbono\": 1,\r\n    \"Nombre\": \"No abona\"\r\n  },
\r\n  {\r\n    \"IdAbono\": 2,\r\n    \"Nombre\": \"Abono orgánico\"\r\n  },
\r\n  {\r\n    \"IdAbono\": 3,\r\n    \"Nombre\": \"Fertilizante químico\"\r\n  },
\r\n  {\r\n    \"IdAbono\": 4,\r\n    \"Nombre\": \"Combinación\"\r\n  }\r\n]"

in my application I have this:

private void ClientGetTablaAbono(string RequestURI)
        {
            string resultado = string.Empty;
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:52143/");
            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;
                List<Abono> TAbono = new List<Abono>();

                //AQUI EL ERROR
                TAbono = JsonConvert.DeserializeObject<List<Abono>>(resultado);
            }
            else
            {
                resultado = response.IsSuccessStatusCode.ToString();
                richTextBox1.Text = resultado;
            }
        }

My Class Pass is this:

  public class Abono
        {
            public int IdAbono { get; set; }

            public string Nombre { get; set; }
        }

ERROR

Newtonsoft.Json.JsonSerializationException: 'Error converting value "[
  {
    "IdAbono": 1,
    "Nombre": "No abona"
  },
  {
    "IdAbono": 2,
    "Nombre": "Abono orgánico"
  },
  {
    "IdAbono": 3,
    "Nombre": "Fertilizante químico"
  },
  {
    "IdAbono": 4,
    "Nombre": "Combinación"
  }
]" to type 'System.Collections.Generic.List'1[ApiRestConsumer.Form2+Abono]'. Path '', line 1, position 308.'

ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List'1[ApiRestConsumer.Form2+Abono].
    
asked by Efrain Mejias C 22.11.2018 в 14:03
source

1 answer

1

Apparently the issue is in the way the server is returning the data. My idea is that since you are serializing the datatable using JsonConvert then the api may be doing a second serialization and therefore the json that you are receiving is not exactly deserializable, at least not without first reversing the first serialization.

Deserialize first to string.

On the line before deserializing the answer, make a first deserialization to string.

List<Abono> TAbono = new List<Abono>();

//Deserializamos primero a string. 
resultado = JsonConvert.DeserializeObject<string>(resultado);

//AQUI EL ERROR (AHORA DEBERIA FUNCIONAR CORRECTAMENTE)
TAbono = JsonConvert.DeserializeObject<List<Abono>>(resultado);

What to do next? (If the first point works)

If the previous point works, it means that your server is sending the data not in the best possible way. I would recommend making some adjustments but wait to see if this is definitely.

I do not know exactly which variant of web api you have (if it's net core, or web api 2.x or other). But in any case the answer of the api should be a json string and not a json string serialized to string.

I hope it serves you.

    
answered by 22.11.2018 / 15:30
source