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());
Run Code Online (Sandbox Code Playgroud)
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?
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",
...
}
]
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4581 次 |
| 最近记录: |