首页 > 解决方案 > 如何反序列化我的 JSON 字符串数组以获取我的用户名?

问题描述

正如您在我的 PHP 脚本中看到的那样,我编写了一个查询,通过使用唯一 ID 从特定用户(登录时)获取所有用户数据。当我得到我的 JSON 字符串时,我只想要用户名。这个用户名我想在我的模拟器屏幕上显示:

PHP 代码(不用担心 SQL 注入 --> 稍后我会修复它)

<?php

$db = new mysqli('localhost', 'root', '', 'test');

$Id = mysqli_real_escape_string($db, $_POST['Id']);

$res = mysqli_query($db, "SELECT * from User WHERE Id = '$Id'");

$rows = array();

while($r = mysqli_fetch_assoc($res)) 
{
    $rows[] = $r;
}

echo json_encode($rows);

?>

Xamarin-Code 所以我只想反序列化 json 字符串的用户名,然后在模拟器屏幕上显示它。有人可以帮我反序列化用户名对象吗?在此代码中,“List”和“res”带有红色下划线...

    public async void GetUserData()
    {
        user u = new user();

        HttpResponseMessage res;

        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("Id", u.Id)
        });

        res = await client.PostAsync("http://10.0.2.2/DATA/USER/DataByID/Data.php", content);

        var user = JsonConvert.DeserializeObject<List>(res); // 'res' and '<List>' are underlined

        u.Username = users[1]; // I want to refer to the second property in the json string (Username)

        BindingContext = u; // displaying the Username on the screen of the emulator
    }

JSON - 字符串

[{"Id":"13","Username":"aze","Email":"aze@aze.be","Passwd":"0a5b3913cbc9a9092311630e869b4442","Age":"27"}]

标签: phpjsonxamarin.formsjson-deserialization

解决方案


var json = await result.Content.ReadAsStringAsync();
var users = JsonConvert.DeserializeObject<List<user>>(json);
u = users[0];
// u will now contain all of your user properties
BindingContext = u;

推荐阅读