0

I'm trying to fill my combo box with some API data but I have a problem with my JSON.

API Call:

string URL = @"https://localhost:44306/api/user/68/all";
            Uri Urladdress = new Uri(URL);
            HttpWebRequest request = WebRequest.Create(Urladdress) as HttpWebRequest;
            request.Headers["X-AccessToken"] = AccessToken;
            request.Method = "GET";
            request.ContentType = "application/json";
            string results = string.Empty;
            HttpWebResponse response;
            using (response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                results = reader.ReadToEnd();
            }

            List<Json> lsObj = JsonConvert.DeserializeObject<List<Json>>(results);

            foreach (Json obj in lsObj)
            {
                for (int i = 0; i < obj.Users.Count(); i++)
                {
                    friends.Items.Add(obj.Users[i].UserId);
                }
            }

JSON class:

    public class Json
    {
        public List<User> Users { get; set; }
    }

    public class User
    {
        public int UserId { get; set; }
        public string Username { get; set; }
        public string FullName { get; set; }
        public object Password { get; set; }
    }

API response:

{"Users":[{"UserId":68,"Username":"Rob","FullName":"Rob test","Password":null},{"UserId":69,"Username":"Test","FullName":"TestRob","Password":null}]}

Visual studio returns an error on obj.Users.UserId on UserId

Screenshot error message

'User[]' does not contain a definition for 'UserID' and no accessible extension method 'UserId' accepting a first argument of type 'User[]' could be found (are you missing a using directive or an assembly reference?)

Is there a simple way to fix this problem?

Rob
  • 176
  • 1
  • 14

2 Answers2

0

You are trying to access the User property from the collection Users, try

            foreach (Json obj in lsObj)
            {
               foreach (User user in lsObj.Users)
               {             
                   friends.Items.Add(user.UserId);
               }
            }
  • that returns a new error ```Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[IOweYou.Frontend.Json]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. ``` – Rob Jun 11 '19 at 21:29
  • ```To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'Users', line 1, position 9.'``` – Rob Jun 11 '19 at 21:29
  • check this answer: https://stackoverflow.com/questions/22557559/cannot-deserialize-the-json-array-e-g-1-2-3-into-type-because-type-requ – Francisco Marão Jun 11 '19 at 21:40
0

Because there's an array.. you need an index

obj.Users[0].UserId  //will get you 68

obj.Users[1].UserId //will get you 69

Consider changing your model from

User[] Users {get; set;}

To

List<User> Users {get; set;}

OR

I recommend that in your second loop, use a for loop (and leave your model alone if you take this route)

for(int i = 0; i < obj.Users.Count(); i++)
{
    friends.Items.Add(obj.Users[i].UserId);
}
jPhizzle
  • 487
  • 1
  • 5
  • 16
  • i've still a strange error message [link](https://ibb.co/KDmwGBB) and my lsObj seems to be empty..... – Rob Jun 11 '19 at 22:12
  • Have you tried changing the User[] to List? Yeah I think that's the issue. Because User[] is an array, and in you you're trying to deserialize a List. – jPhizzle Jun 11 '19 at 22:16
  • Yes i did change User to List – Rob Jun 11 '19 at 22:27
  • what's IOweYou.Frontend.Json? – jPhizzle Jun 11 '19 at 22:44
  • IOweYou is my app name – Rob Jun 11 '19 at 22:52
  • Frontend because i've also a backend where my database connections are made – Rob Jun 11 '19 at 22:53
  • .Json i'm nog sure? – Rob Jun 11 '19 at 22:53
  • So the error message is saying is that IOweYou.Frontend.Json is an array and an object cannot be mapped to it, maybe the issue is somewhere in that Frontend area – jPhizzle Jun 11 '19 at 22:54
  • 1
    ``` var result = JsonConvert.DeserializeObject(results); var firstNames = result.Users.Select(p => p.Username).ToList(); for (int i = 0; i < result.Users.Count(); i++) { friends.Items.Add(result.Users[i].Username); }``` – Rob Jun 12 '19 at 07:24