【发布时间】:2017-07-04 06:51:06
【问题描述】:
我在反序列化 JSON 对象时在 Xamarin 跨平台中收到以下错误。我试过用字典来做。但是,一切都给了我同样的例外。
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
我的 JSON 对象类:
public class jsonobjectclass
{
public class User
{
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string current_group { get; set; }
public List<UserGroups> user_groups { get; set; }
}
public class UserGroups
{
[JsonProperty("10")]
public string Student { get; set; }
[JsonProperty("15")]
public string Tutor { get; set; }
[JsonProperty("11")]
public string Parent { get; set; }
}
public class Token
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string token_type { get; set; }
public string scope { get; set; }
public string refresh_token { get; set; }
public string error { get; set; }
}
public class UserResponse
{
public string msg { get; set; }
public List<User> data { get; set; }
public bool error { get; set; }
}
}
我的反序列化 JSON 代码:
public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
{
var jsonObject = new jsonobjectclass.UserResponse();
string readHttpResponse;
using (var httpClient = new HttpClient())
{
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
{
httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObject = JObject.Parse(readHttpResponse);
try
{
jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
}
catch(Exception ex)
{
string excep = ex.ToString();
readHttpResponse = excep;
}
}
}
}
return jsonObject;
}
我的 JSON 字符串:
{{
"msg": null,
"data": {
"name": "geoit",
"email": "rokesh@geoit.in",
"phone": null,
"current_group": "11",
"user_groups": {
"11": "Parent"
}
},
"error": false
}}
请帮我解决这个问题。
谢谢, 罗克什
【问题讨论】:
-
发布你的 json 字符串
-
阅读How to Ask 并创建一个minimal reproducible example。所有 HTTP 代码都无关紧要,相关部分,即 JSON 字符串,不在您的问题中。
-
在收到响应后显示 readHttpResponse 的值
-
这不是一个有效的 JSON。使用在线验证器来验证 json.. jsonlint.com/https://jsonlint.com
-
你真的有像 {{ }} 或 {} 这样的双括号
标签: c# .net json xamarin serialization