Reese
Reese

Reputation: 253

Error during JSON parsing

JSON string:

[{"id":"1","username":"admin","password":"anymd5hash","rank":"2"}]

following code:

Newtonsoft.Json.Linq.JObject userData;
userData = Newtonsoft.Json.Linq.JObject.Parse(result);
MessageBox.Show(userData["username"].ToString());

When I execute this code, there will be an error:

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.

I'm pretty sure, that this code has worked in another project.

What is my mistake?

Upvotes: 0

Views: 5048

Answers (1)

Alberto Chiesa
Alberto Chiesa

Reputation: 7350

You are not providing a Json object, you are providing a Json Array with a single object inside it:

// Json object:
{
  "id": "1",
  ...
}

//Json array:
[
  {
    "id": "1",
    ...
  }
]

So, either you change the json or the Json.Net code (and look for JArray as in the comments).

BTW, if you know the properties in advance you really should create a .Net class to be used to contain the deserialization.

public class UserData
{
  public string id { get; set; }
  public string username { get; set; }
  public string password { get; set; }
  public string rank { get; set; }
}

// and then, in your code:
List<UserData> userData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<UserData>>(result);

Upvotes: 5

Related Questions