bukenya micheal
bukenya micheal

Reputation: 69

Am getting an error while reading json data received. Am developing a UWP using C# which reads data from json

public class BMIRSProxy
{
    static string json_url = string.Format("http://localhost:8081/bmirs_2015/php_scripts/get_staff_members.php");
    public async static Task<StaffMember> GetStaffMember()
    {
        var http = new HttpClient();
        var response = await http.GetAsync(json_url);
        var result = await response.Content.ReadAsStringAsync();
        var serializer = new DataContractJsonSerializer(typeof(StaffMember));
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
        var data = (StaffMember)serializer.ReadObject(ms);
        return data;
    }
}

[DataContract]
public class StaffMember
{
    [DataMember]
    public string first_name { get; set; }
    [DataMember]
    public string last_name { get; set; }
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public string profile { get; set; }
    [DataMember]
    public string image_uri { get; set; }
}

Above is the class I created. but when I can the method GetStaffMember within a button created , no data is output. when I debugged I got two errors from the MemomryStream instance ms as below :

  1. List item

ReadTimeout = 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

  1. List item

WriteTimeout = 'ms.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

Below is the code i used to call the method GetStaffMember

private async void Button_Click(object sender, RoutedEventArgs e)
{
    StaffMember myStaffMember = await BMIRSProxy.GetStaffMember();
}

Your help will be highly appreciated because am stuck now

Upvotes: 2

Views: 382

Answers (1)

Raja Nadar
Raja Nadar

Reputation: 9499

Looks like your JSON string is an array containing 1 element. So let us deserialize as an array and select the only element for your data binding

public async static Task<StaffMember> GetStaffMemberAsync()
{
    var http = new HttpClient();
    var response = await http.GetAsync(json_url);
    var result = await response.Content.ReadAsStringAsync();

    var data = (JsonConvert.DeserializeObject<List<StaffMember>>(result))[0];
    return data;
}

Upvotes: 1

Related Questions