error when deserializar (csharp - Xamarin) a json (php)

0

Classes

public class Usuario
{
    public string id { get; set; }
    public string nombre { get; set; }
    public string nick { get; set; }
    public string password { get; set; }
    public string email { get; set; }
}

public class T
{
    public int success { get; set; }
    public string message { get; set; }
    public List<Usuario> Usuario { get; set; }
}

call ..

 var client = new HttpClient();
                    client.BaseAddress = new Uri(urlBase);
                    var url = string.Format("{0}{1}", servicePrefix, controller);
                    var response = await client.GetAsync(url);

                    var result = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                    {
                        return new Response
                        {
                            IsSuccess = false,
                            Message = result,
                        };
                    }


                var list = JsonConvert.DeserializeObject<List<T>>(result);
                    return new Response
                    {
                        IsSuccess = true,
                        Message = "Ok",
                        Result = list,
                    };
                }
                catch (Exception ex)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = ex.Message,
                    };
                }

php

if ($result = $mysqli->query("SELECT ID,NOMBRE,NICK,PASSWORD,EMAIL FROM  Usuario")) {

    // check for empty result
        if (mysqli_num_rows($result) > 0) {
            // looping through all results
            // products node

            $response["success"] = 1;
            $response["message"] = "ok";

             $response["Usuario"] = array();

            while ($row = mysqli_fetch_array($result)) {
                // temp user array
                $USUARIO = array();
                $USUARIO["id"] = $row["ID"];
                $USUARIO["nombre"] = $row["NOMBRE"];
                $USUARIO["nick"] = $row["NICK"];
                $USUARIO["password"] = $row["PASSWORD"];
                $USUARIO["email"] = $row["EMAIL"];

                array_push($response["Usuario"], $USUARIO);

            }

            echo json_encode($response);
        } else {
            // no products found
            $response["success"] = 0;
            $response["message"] = "No Usuarios";

            // echo no users JSON
            echo json_encode($response);
        }

    /* liberar el conjunto de resultados */
    $result->close();
}

the values obtained are

 var response = await client.GetAsync(url);

// return this to me

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Mon, 15 Oct 2018 17:18:29 GMT
Server: Apache
X-Powered-By: PHP/7.1.18
Vary: Accept-Encoding,User-Agent
Keep-Alive: timeout=5
Connection: Keep-Alive
Content-Length: 168
Content-Type: text/html; charset=UTF-8
}}

and

var result = await response.Content.ReadAsStringAsync();

// here he returns me

"{\"success\":1,\"message\":\"ok\",\"Usuario\":[{\"id\":\"1\",\"nombre\":\"G_nom\",\"nick\":\"J_nick\",\"password\":\"J_pass\",\"email\":\"J_email\"},{\"id\":\"2\",\"nombre\":\"U_nom\",\"nick\":\"U_nick\",\"password\":\"U_pass\",\"email\":\"U_email\"}]}"

the error is

{Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'1[lands.Models.Land]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'success', line 1, position 11.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00397] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x0006d] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0 
  at lands.Services.ApiService+<GetList>d__3'1[T].MoveNext () [0x001a2] in C:\xamarin17\lands\lands\lands\Services\ApiService.cs:142 }

What am I doing wrong? or am I missing something?

    
asked by Gerard Cáceres 15.10.2018 в 19:25
source

1 answer

2

You are deserializing a list:

var list = JsonConvert.DeserializeObject<List<T>>(result);

but your json returns a single object with 3 properties actually.

{"success":1,
 "message":"ok",
 "usuario": [{...}. {...}]
 ...
}

Change your code in this way, it should work (not a list, but a T object)

var list = JsonConvert.DeserializeObject<T>(result);
return new Response
{
   IsSuccess = true, // o list.success si quieres usar lo que viene desde PHP
   Message = "Ok", //o list.message si quieres usar lo que viene desde PHP
   Result = list.Usuario,
};
    
answered by 16.10.2018 / 12:59
source