We are creating an application in Xamarin that is aimed at the Android market. We need to pull a list of objects off of the Wordpress API in order to populate a list view.
The code seems to be erroring at the deserialisation part of the code. EventLW is a ListView on the front-end of the application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.Net.Http;
using Newtonsoft.Json;
namespace StudioDen.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Events : ContentPage
{
public Events()
{
InitializeComponent();
GetProducts();
}
private async void GetProducts()
{
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("http://studioden.uk/wp-json/wp/v2/events/");
var events = JsonConvert.DeserializeObject<List<Events>>(response);
eventLV.ItemsSource = events;
}
}
}
Newtonsoft.Json.JsonReaderException Message=Unexpected character encountered while parsing value: {. Path '[0].title', line 1, position 341.
Any ideas on what is going wrong here? I followed a youtube tutorial and I don't think it is an issue with the code directly but with the Json string from the call.
You are deserializing the response object and not the response content. The following is what you need to do
private async void GetProducts()
{
HttpClient client = new HttpClient();
var response = await
client.GetAsync("http://studioden.uk/wpjson/wp/v2/events/");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync ();
var events = JsonConvert.DeserializeObject<List<Events>>(content);
}
else
{
//Do stuff based on the status, was the content found,
//was there a server error etc.
}
...
}
Explanation on the above code
You send a request and get a response object which includes headers, status code, messages etc.
you check that the request is successful(if it isn't you want to handle a bad request or server error etc)
you then need to read the response content into a string then deserialize the json in that string value. before finally populating your list view