【问题标题】:Having a problem with json object serialization using refit使用 refit 进行 json 对象序列化时遇到问题
【发布时间】: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&lt;RootObject&gt;
  • 我试过 Task GetCategories();但对于 @A Friend 的分类仍然为空
  • 尝试更改您的 Datum 对象。将 Subcat 的类型从 List 更改为 List

标签: c# json api xamarin.forms json.net


【解决方案1】:

如果有人遇到同样的问题,这就是我用来解决的方法,我没有使用 refit,只是使用常规 HTTP 请求和 NewtonSoft for Json

模型

public class Category
    {
        public bool status { get; set; }
        public object message { get; set; }
        public IList<Datum> data { get; set; } 

    }

    public class SubCat
    {
        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 int courses_count { get; set; }
        public string menu_status { get; set; }
        public IList<object> subCat { get; set; }
    }

    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 IList<SubCat> subCat { get; set; }
    }

}

API 调用请求

async Task CallApi()
        {
            string Url = "your Link Goes Here";
            HttpResponseMessage response;
            string return_value = "empty";

            try
            {
                HttpClient _client = new HttpClient();

                response = await _client.GetAsync(Url);

                if (response.IsSuccessStatusCode)
                {
                    return_value = await response.Content.ReadAsStringAsync();
                    var categs = JsonConvert.DeserializeObject<Category>(return_value).data;
                    CategList.ItemsSource = categs;
                }
                else
                {
                    return_value = "not successful";
                }
            }
            catch (Exception ex)
            {
                return_value = (string)ex.Message + " :: " + ex.InnerException.Message;
            }
        }

【讨论】:

    【解决方案2】:

    您应该尝试将 JSON 反序列化为 JObject,然后通过键访问其属性:

    var obj = JsonConvert.DeserializeObject<JObject>("Json content as a string");
    
    var prop1 = obj["Key1"];
    var prop2 = obj["key2"]["subkey"];
    

    【讨论】:

      【解决方案3】:

      您正在尝试反序列化一个列表,但是您正在接收一个 RootObjet。

      改变这个:

       [Get("/category")]
              Task<RootObject> GetCategories();
      

      【讨论】:

      • 我试过 Task GetCategories();但类别仍然为空
      • 你现在有什么异常吗?
      • 不,它没有给出例外,但仍然给我归类为 null
      • 您是否检查过是否收到回复?您的错误已解决。现在你很可能面临另一个问题。
      【解决方案4】:

      在我的情况下,我没有从调试器中得到任何反馈,没有错误只是一个空白对象。对我有用的是在 Get 调用之前初始化要反序列化的对象。

      对于这个例子(使用改装),它会是这样的:

          var rootObject = new RootObject();
      
          var apiResponse = RestService.For<IGDGAPI>("API Link Here");
          rootObject = await apiResponse.GetCategories();
      

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多