I'm trying to access the php API on our server that basically outputs a json string as a result. The string is a list of json objects and I'm trying to deserialize them into a List of a class I have defined in the data model of my app. The problem is, when I try to just output the result in the console in my http testing project, I get a nullreferenceobject exception even though the address is completely correct and gives me a json object as expected.
Here is my async method in the myClient class:
public async Task<List> getUsers()
{
var client = new HttpClient();
// I just split up the entire address into baseAddress, the phpScript and the username so that I can change depending on what I need to Get from the server
var response = await client.GetAsync(baseAddress + phpScript + username);
var userJson = response.Content.ReadAsStringAsync().Result;
var rootObject = JsonConvert.DeserializeObject<userRoot>(userJson);
return rootObject.users;
}
Then in my test Program:
static void Main(string[] args)
{
var client = new myClient();
var userList= client.getUserFriends(action, controller);
foreach (User u in userList.Result) // this is where it breaks telling me the object is null
{
Console.WriteLine("Reading firstname: ");
Console.WriteLine(u.firstName);
}
}
Here is part of my model:
public class User
{
// class generated by copying the address into json2csharp.com
public string userID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string userName { get; set; }
}
public class userRoot // also generated by json2csharp.com
{
public List<User> users { get; set; }
public bool sucess { get; set; }
}
Like I mentioned, the address does respond with the correct json string, but there seems to be a problem somewhere in the conversion or the async method, I really can't tell what's going wrong...