1

I like to get the first value of JSON array.

My JSON:

{
    "userlist": [
        {
            "id": 123,
            "name": "Max",
        }
    ],
}

What I have:

public int JSONId(string JSONstring)
        {
            JObject responseJSON = JObject.Parse(ResponseGETSearchForCorrectID);
            int id = (int)JArray.Parse(ResponseGETSearchForCorrectID).Children()["userlist"]["id"].First();

            return id;
        }

But I get this error: Newtonsoft.Json.JsonReaderException: 'Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.'

I tried also:

int idPackage = responseJSON["userlist"]["id"].Values;

But doesn`t work too because I get an exception with the info, that this is an array.

What I do wrong here? Have someone a soulution?

Thank you.

3
  • trailing comma will break it Commented May 19, 2020 at 0:32
  • your JSON is invalid. remove , after the ] Commented May 19, 2020 at 0:32
  • I edited and made the JSON file shorter to understand more easily. There is more stuff after ] but thanks for the info Commented May 19, 2020 at 0:35

2 Answers 2

2

Try it this way

int idPackage = responseJSON["userlist"][0]["id"].Value<int>();

Since userliat is an array, you have to access the objects via index.

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

Comments

0

Try this way:

var obj = JsonConvert.DeserializeObject(str);
int id = obj.userlist[0].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.