0

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?

3
  • 3
    Remove the [ and ] from your string and try again. It's an array. Commented Apr 3, 2016 at 17:26
  • 3
    Or more likely, switch to Newtonsoft.Json.Linq.JArray.Parse. That will accept your existing input. JToken would also work for either arrays (what you've got) or objects. Commented Apr 3, 2016 at 17:28
  • 1
    If you don't know in advance if the root object is an array or object, use JToken.Parse(). Commented Apr 3, 2016 at 17:52

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

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.