0

New to both C# and to using JSON. Trying to make something that works with some JSON from a web API in the following format. Would like to loop through and store the secondUser_id and and the status for later use.

{
  "user_list": [
    {
      "user_id": "12345678910",
      "secondUser_id": "5428631729616515697",
      "member_since": "1521326679",
      "member_since_date": "2018-03-32",
      "function": "test",
      "rank_int": "1",
      "status": "0"
    },
    {
      "user_id": "11345638910",
      "secondUser_id": "5428631729616515697",
      "member_since": "1521326679",
      "member_since_date": "2018-03-32",
      "function": "test",
      "rank_int": "1",
      "status": "0"
    },
    {
      "user_id": "13452578910",
      "secondUser_id": "12390478910",
      "member_since": "12316578910",
      "member_since_date": "2018-03-32",
      "function": "test",
      "rank_int": "1",
      "status": "0"
    }
  ],
  "returned": 3
}
string jsonUrl = GetJSON("url");
JObject UsersJObject = JObject.Parse(jsonUrl);
JToken user = UsersJObject["user_list"].First["secondUser_id"];

Console.WriteLine("User ID: " + user);

This will get the first entry but I'm not sure what to use for a enumerator?

1
  • 1
    Consider deserializing Commented Mar 23, 2018 at 1:11

2 Answers 2

2

try something like this:

foreach (var obj in UsersJObject["user_list"] as JArray)
{
    Console.WriteLine(obj["secondUser_id"]);
}

You can iterate over elements of a JArray, and user_list will be of that type, cast it and you can iterate it in a foreach loop.

Sign up to request clarification or add additional context in comments.

Comments

0

I will recommend you to use JsonConvert.DeserializeObject<T>.

This can help you to use objects easily

public class UserList
{
    public string user_id { get; set; }
    public string secondUser_id { get; set; }
    public string member_since { get; set; }
    public string member_since_date { get; set; }
    public string function { get; set; }
    public string rank_int { get; set; }
    public string status { get; set; }
}

public class JsonData
{
    public List<UserList> user_list { get; set; }
    public int returned { get; set; }
}

Use like this.

string jsonUrl = GetJSON("url");

JsonData UsersJObject = JsonConvert.DeserializeObject<JsonData>(jsonUrl);

foreach (var obj in UsersJObject.user_list)
{
    Console.WriteLine(obj.secondUser_id);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.