首页 > 解决方案 > How to display data on Xamarin.Android edit text using Web API

问题描述

I'm trying to display the data from SQL server using web API, get method on edit text in Xamarin.Android. The data will display on the edit text once the button is clicked. I've followed all the steps (exactly) as in the YouTube tutorial but unfortunately, the data did not show up on the edit text, instead it shows JSON format on the screen. What should I do to fix this problem?

I've tried using Web services, still didn't show up.

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.PersonalInfo);

    ActionBar.SetDisplayHomeAsUpEnabled(true);

    EditText email = FindViewById<EditText>(Resource.Id.txtEmail);
    EditText firstName = FindViewById<EditText>(Resource.Id.txtFirstName);
    EditText lastName = FindViewById<EditText>(Resource.Id.txtLastName);
    EditText gen = FindViewById<EditText>(Resource.Id.txtGender);
    EditText ic = FindViewById<EditText>(Resource.Id.txtIC);
    EditText address = FindViewById<EditText>(Resource.Id.txtAddress);
    EditText phoneNo = FindViewById<EditText>(Resource.Id.txtPhoneNo);
    EditText username = FindViewById<EditText>(Resource.Id.txtUsername);
    EditText password = FindViewById<EditText>(Resource.Id.txtPwd);
    EditText payment = FindViewById<EditText>(Resource.Id.txtPayMethod);
    Button btnGetAcc = FindViewById<Button>(Resource.Id.btnGetAcc);

    btnGetAcc.Click += async delegate
    {
        VehicleRecord vehicRec = null;
        HttpClient client = new HttpClient();
        string url = "http://192.168.0.135/PMSAPI/api/clients/" + username.Text.ToString();
        var result = await client.GetAsync(url);
        var json = await result.Content.ReadAsStringAsync();

        try
            {
                vehicRec = Newtonsoft.Json.JsonConvert.DeserializeObject<VehicleRecord>(json);
                if (vehicRec == null)
                {
                    //check for an array just in case
                    var items = JsonConvert.DeserializeObject<VehicleRecord[]>(json);
                    if (items != null && items.Length > 0)
                    {
                        vehicRec = items[0];
                    }
                }
            }
            catch (Exception ex) { }
    };
}

The expected output should display data from SQL server on edit text but the actual output is it display all the data in JSON-format.

The actual output:
The actual output

标签: c#visual-studioasp.net-web-apixamarin.androidandroid-edittext

解决方案


您的代码的逻辑是显示 JSON if vehicRec == null

图像中显示的 JSON 是一个数组。注意[]包裹 JSON 对象的方括号。

[{....}]

这意味着要求反序列化到一个对象会失败。重构代码以反序列化为数组,然后从结果中提取所需的对象。

//...omitted for brevity

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

try {
    vehicRec = Newtonsoft.Json.JsonConvert.DeserializeObject<VehicleRecord>(json);
    if(vehicRec == null) {
        //check for an array just in case
        var items = JsonConvert.DeserializeObject<VehicleRecord[]>(json);
        if(items != null && items.Length > 0) {
            vehicRec = items[0];
        }
    }
}
catch (Exception ex) { }

if (vehicRec == null)
{
    Toast.MakeText(this, json, ToastLength.Short).Show();
}
else
{
    firstName.Text = vehicRec.firstName;
    lastName.Text = vehicRec.lastName;
    gen.Text = vehicRec.gender;
    ic.Text = vehicRec.icNo;
    address.Text = vehicRec.address;
    phoneNo.Text = vehicRec.phoneNo;
    username.Text = vehicRec.username;
    password.Text = vehicRec.password;
    payment.Text = vehicRec.paymentMethod;
}

//...omitted for brevity

另请注意,在 JSON 中,数组中有多个项目。我建议您考虑使用列表来显示数组中的记录。

上面的代码将仅显示数组中的第一项,但可以轻松重构以将数组用作列表视图的数据源。

还注意到 JSON 中的字段名称与正在填充的类的名称不匹配。这将导致属性无法获得任何值。

从您之前的一个问题中,我可以看到您将课程定义为

public class VehicleRecord {
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string gender { get; set; }
    public string icNo { get; set; }
    public string address { get; set; }
    public string phoneNo { get; set; }
    public string email { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string plateNo { get; set; }
    public string model { get; set; }
    public string col { get; set; }
    public string paymentMethod { get; set; }
}

但是图像中显示的 JSON 的所有字段都以cl.

您需要添加一个映射,以便 JsonConverter 知道如何填充该类

public class VehicleRecord {
    [JsonProperty("clFirstName")]
    public string firstName { get; set; }
    [JsonProperty("clLastName")]
    public string lastName { get; set; }
    [JsonProperty("clGender")]
    public string gender { get; set; }


    //...etc
}

您最好使用 JSON 解析器为您生成类,该类还包括映射属性的属性。


推荐阅读