【发布时间】:2019-06-13 12:05:07
【问题描述】:
我是 Xamarin 的新手,所以请原谅。我有一个 json 对象,我正在尝试使用 refit 对其进行反序列化,但我认为由于类不正确而出现错误
这是json对象
{
"status": true,
"message": null,
"data": [
{
"menu_id": 46,
"menu_title": "media",
"menu_parent": 0,
"menu_sort": "1",
"menu_status": "1",
"courses_count": 4,
"subCat": [
{
"menu_id": 48,
"menu_title": "media",
"menu_parent": 46,
"menu_sort": "1",
"courses_count": 0,
"menu_status": "1",
"subCat": [
{
"menu_id": 50,
"menu_title": "media",
"menu_parent": 48,
"menu_sort": "1",
"courses_count": 0,
"menu_status": "1",
"subCat": []
},
{
"menu_id": 51,
"menu_title": "media",
"menu_parent": 48,
"menu_sort": "1",
"courses_count": 0,
"menu_status": "1",
"subCat": []
}
]
},
{
"menu_id": 49,
"menu_title": "media",
"menu_parent": 46,
"menu_sort": "1",
"courses_count": 0,
"menu_status": "1",
"subCat": []
}
]
},
{
"menu_id": 47,
"menu_title": "media",
"menu_parent": 0,
"menu_sort": "2",
"menu_status": "1",
"courses_count": 2,
"subCat": []
},
{
"menu_id": 55,
"menu_title": "CS",
"menu_parent": 0,
"menu_sort": "3",
"menu_status": "1",
"courses_count": 2,
"subCat": []
}
]
}
我使用 json2csharp 来转换 json,这就是我得到的
public class Datum
{
public int menu_id { get; set; }
public string menu_title { get; set; }
public int menu_parent { get; set; }
public string menu_sort { get; set; }
public string menu_status { get; set; }
public int courses_count { get; set; }
public List<object> subCat { get; set; }
}
public class RootObject
{
public bool status { get; set; }
public object message { get; set; }
public List<Datum> data { get; set; }
}
这是使用 refit 的代码 界面
public interface IGDGAPI
{
[Get("/category")]
Task<List<RootObject>> GetCategories();
}
代码
var apiResponce = RestService.For<IGDGAPI>("API Link Here");
var Categs = await apiResponce.GetCategories();
CategList.ItemsSource = _categs;
当我在 Categs 插入断点时,它给了我 null 这是错误信息
Unhandled Exception:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'GDG6OCT.Models.RootObject[]' 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 'status', line 1, position 10.
【问题讨论】:
-
错误很明显,根对象是.. 一个对象.. 但你试图反序列化为
List<RootObject> -
我试过 Task
GetCategories();但对于 @A Friend 的分类仍然为空 -
尝试更改您的 Datum 对象。将 Subcat 的类型从 List
标签: c# json api xamarin.forms json.net