将 JsonObject 转换为 List

本文关键字:List JsonObject 转换 | 更新日期: 2023-09-27 17:56:38

>我有这个 json 值,我想将其转换为列表

[{
    "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"
}]

这是我到目前为止的代码:

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;
                }
            }

这是我想要存储值的类:

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; }

    }

我怎样才能做到这一点?提前谢谢你!

将 JsonObject 转换为 List<T>

您需要

下载此Nuget包(右键单击项目>管理器Nuget包)

然后你可以使用:

string json = null;
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
    json = stream.ReadToEnd();
}
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);

如果您使用的是 HttpClient:

var response = await httpClient.GetAsync(url);
string json = await response.Content.ReadAsStringAsync();
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
相关文章: