-2

Hi I want to read Id from JSON object which returns from Web Service :

[{"id":11,"username":"test5"}]

Code:

HttpResponseMessage response = null;

using (response = httpClient.PostAsync(url, content).Result)
{
    try
    {
        response.EnsureSuccessStatusCode(); //200 Ok
        string responJsonText = response.Content.ReadAsStringAsync().Result;
        JObject res = JObject.Parse(responJsonText);
       //if ((int)res["id"][0] > 0)
       // {
            var uid = (int)res["id"][0];
            if (uid > 0)
            {
                return uid;
            }
            else
            { return 0; }
       // }
       // else
       //{ return 0; }
    } 

How i can read the Id and username from Json Response using C#?

I get an exception with the following message:

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Jim Lobo
  • 471
  • 1
  • 7
  • 22
  • Possible duplicate of [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Josh Oct 30 '18 at 13:32
  • what exact issue / error are you facing with your code? I wonder if the async operation is a problem - you perhaps need to await it otherwise it won't be ready before you move to the next line and try to read the response. `res["id"][0]` also doesn't make much sense because the id is not an array. – ADyson Oct 30 '18 at 13:42

1 Answers1

7

Solution 1 - deserialize into C# models:

You can create a model that matches your json structure:

public class User
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }
}

And then deserialize the json string, using Newtonsoft.Json nuget package as follows:

string json = @"[{""id"":11,""username"":""test5""}]";
var users = JsonConvert.DeserializeObject<List<User>>(json);

Solution 2 - parsing the json using JArray

string json = @"[{""id"":11,""username"":""test5""}]";

JArray array = JArray.Parse(json);
int id = array.First["id"].Value<int>();
string username = array.First["username"].Value<string>();

I'm assuming the array will contain at least 1 element and there will be an id and username property. Proper error handling code should be added.

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86