meluluji meluluji - 4 months ago 33
JSON Question

Convert JsonObject to List<T>

I have this json value that I want to convert to a List

[{
"id_cuenta": 1,
"nombre": "Mercedes Luj\u00e1n",
"apellido": "Llano",
"ci": 123,
"telefono": 123456789,
"dispositivo_id": "355790037549877",
"password": "holaa",
"created_at": "2016-07-02 11:36:57",
"updated_at": "2016-07-09 09:56:53"
}]


This is my code so far:

private List<cuentaObtener> mCuenta;

btnLogIn.Click += async(object sender, EventArgs e) =>
{
string url = "http://localhost:8000/api/v1/cuenta_ci/" + ci.Text + "";
JsonValue json = await ObtenerCi(url);

private async Task<JsonValue> ObtenerCi(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";

// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

//Code to convert JsonObject to List<T>


// Return the JSON document:
return jsonDoc;
}
}


This is my class where I want to store values:

public class cuentaObtener
{
public int id_cuenta { get; set; }
public string nombre { get; set; }
public string apellido { get; set; }
public int ci { get; set; }
public int telefono { get; set; }
public string dispositivo_id { get; set; }
public string password { get; set; }


}


How can I achieve this? Thank you in advance!

Answer

You need to download this Nuget Package (Right Click Project > Manager Nuget Packages)

Then you can use :

string json = null;
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
    json = stream.ReadToEnd();
}

List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);

If you're using HttpClient:

var response = await httpClient.GetAsync(url);
string json = await response.Content.ReadAsStringAsync();
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
Comments