簡體   English   中英

使用restsharp反序列化JSON

[英]Deserialize JSON using restsharp

我試圖從Harvest反序列化數據,但它失敗了(沒有錯誤): https//github.com/harvesthq/api#api-json

返回的數據如下所示:

更新 (請參閱底部的完整JSON響應)

我運行下面代碼時的輸出是一個帶有x個帖子的列表,其中每個帖子包含一個id = 0

是否有一個設置或我錯過的東西讓它忽略/解析周圍的[]?

[DeserializeAs(Name = "project")]
public class Project
{
    public int id { get; set; }

    //public string name { get; set; }

    //[DeserializeAs(Name = "created-at")]
    //public DateTime CreatedAt { get; set; }           
}

// The following is the methods to request for testing

public List<Project> GetProjects()
{
    var request = new RestRequest("projects", Method.GET);
    request.RequestFormat = DataFormat.Json;
    return Execute<List<Project>>(request);
}

private T Execute<T>(RestRequest request) where T : new()
{
    var client = new RestClient();            
    client.BaseUrl = BaseUrl;
    client.Authenticator = new HttpBasicAuthenticator(_username, _password);
    var response = client.Execute<T>(request);

    if (response.ErrorException != null)
    {
        const string message = "Error retrieving response.  Check inner details for more info.";
        var exception = new ApplicationException(message, response.ErrorException);
        throw exception;
    }
    return response.Data;
}

從Harvest返回的數據:

[
  {
    "project": {
      "id": 123456,
      "client_id": 219854,
      "name": "Test proj 1",
      "code": "",
      "active": false,
      "billable": true,
      "bill_by": "Tasks",
      "cost_budget": null,
      "cost_budget_include_expenses": false,
      "hourly_rate": null,
      "budget": 8,
      "budget_by": "project",
      "notify_when_over_budget": false,
      "over_budget_notification_percentage": 80,
      "over_budget_notified_at": null,
      "show_budget_to_all": false,
      "created_at": "2014-04-03T09:49:00Z",
      "updated_at": "2014-07-02T11:45:07Z",
      "estimate": 8,
      "estimate_by": "project",
      "hint_earliest_record_at": "2014-04-03",
      "hint_latest_record_at": "2014-04-03",
      "notes": ""
    }
  },
  {
    "project": {
      "id": 234567,
      "client_id": 686547,
      "name": "Test porj 2",
      "code": "",
      "active": true,
      "billable": true,
      "bill_by": "Tasks",
      "cost_budget": null,
      "cost_budget_include_expenses": false,
      "hourly_rate": null,
      "budget": 8,
      "budget_by": "project",
      "notify_when_over_budget": false,
      "over_budget_notification_percentage": 80,
      "over_budget_notified_at": null,
      "show_budget_to_all": false,
      "created_at": "2014-04-03T09:48:28Z",
      "updated_at": "2014-04-15T20:47:29Z",
      "estimate": 8,
      "estimate_by": "project",
      "hint_earliest_record_at": "2014-04-03",
      "hint_latest_record_at": "2014-04-03",
      "notes": ""
    }
  },
  {
    "project": {
      "id": 345678,
      "client_id": 987456,
      "name": "Test proj 3",
      "code": "",
      "active": false,
      "billable": true,
      "bill_by": "Project",
      "cost_budget": null,
      "cost_budget_include_expenses": false,
      "hourly_rate": null,
      "budget": 8,
      "budget_by": "project",
      "notify_when_over_budget": false,
      "over_budget_notification_percentage": 80,
      "over_budget_notified_at": null,
      "show_budget_to_all": false,
      "created_at": "2013-04-26T13:21:35Z",
      "updated_at": "2014-03-30T18:05:24Z",
      "estimate": 8,
      "estimate_by": "project",
      "hint_earliest_record_at": "2013-04-26",
      "hint_latest_record_at": "2013-12-04",
      "notes": "Scriblings from meeting ..."
    }
  }
]

你錯誤地解釋了JSON響應。

[
  {
    "project": {
      "id": 123456
    }
  },
  {
    "project": {
      "id": 234567
    }
  }
]

這是一個包含Project對象的數組。 我不熟悉RestSharp,但這樣的事情應該做:

public class SomeType
{
    public Project project { get; set; }
}
return Execute<List<SomeType>>(request);

您可能希望與項目維護人員取得聯系,但根據文檔 /projects應返回一系列項目。

正如Stijn所提到的,您的服務正在返回一個容器對象的數組,該容器對象具有類型為project的屬性。

我冒昧地使用Stijn建議的修復重新創建代碼示例,請參閱下面的內容。

using RestSharp;
using RestSharp.Deserializers;
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();

            var project = p.GetProjects();
        }

        public class ProjectResult 
        {
            public Project project { get; set; }
        }

        public class Project
        {
            public int id { get; set; }
        }

        public List<ProjectResult> GetProjects()
        {
            var request = new RestRequest("projects", Method.GET);
            request.RequestFormat = DataFormat.Json;
            return Execute<List<ProjectResult>>(request);
        }

        private T Execute<T>(RestRequest request) where T : new()
        {
            var client = new RestClient();
            client.BaseUrl = "http://127.0.0.1:1337/";
            //client.Authenticator = new HttpBasicAuthenticator(_username, _password);
            var response = client.Execute<T>(request);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response.  Check inner details for more info.";
                var exception = new ApplicationException(message, response.ErrorException);
                throw exception;
            }
            return response.Data;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM