我有一個的WebAPI返回以下JSON而我試圖反序列化對象下面便攜式庫錯誤
JSON對象
{
"results": [{
"id": 123456,
"fullName": "Foo Bar",
"localName": null,
"jobPosition": "ME",
"jobCompanyName": "EXTRA",
"jobLocationCountry": "United States of America",
"jobLocationCity": "San Francisco",
"jobCountrySubdivision": "California",
"boards": [],
"restrictionsIndicator": false,
"personRestriction": null,
"jobRestriction": null
}, {
"id": 789101,
"fullName": "Foo Bar",
"localName": null,
"jobPosition": null,
"jobCompanyName": "Unknown",
"jobLocationCountry": "Unknown",
"jobLocationCity": "Unknown",
"jobCountrySubdivision": "Unknown",
"boards": [{
"companyId": 667525,
"companyName": "FOO BAR COMPANY",
"companyOffLimits": null,
"restrictionCategoryId": null
}
],
"restrictionsIndicator": false,
"personRestriction": null,
"jobRestriction": null
}
],
"totalCount": 2,
"pageNumber": 1,
"resultsPerPage": 100
}
C#類
public class Rootobject
{
public Result[] results { get; set; }
public int totalCount { get; set; }
public int pageNumber { get; set; }
public int resultsPerPage { get; set; }
}
public class Result
{
public int id { get; set; }
public string fullName { get; set; }
public object localName { get; set; }
public string jobPosition { get; set; }
public string jobCompanyName { get; set; }
public string jobLocationCountry { get; set; }
public string jobLocationCity { get; set; }
public string jobCountrySubdivision { get; set; }
public Board[] boards { get; set; }
public bool restrictionsIndicator { get; set; }
public int? personRestriction { get; set; }
public int? jobRestriction { get; set; }
}
public class Board
{
public int companyId { get; set; }
public string companyName { get; set; }
public int? companyOffLimits { get; set; }
public object restrictionCategoryId { get; set; }
}
該DLL是一個可移植的類庫,它是.NET 4.5,我有JSON .net(10.0.1)通過nuget安裝,但便攜式庫連接到Mac上的xamarin IOS項目。
如果被反序列化的JSON沒有Boards
它工作得很好,但如果有Board
,我會收到以下消息。
Unable to find a constructor to use for type Board. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'results[1].boards[0].companyId'
我使用的設置是:
var settings = new Newtonsoft.Json.JsonSerializerSettings
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
};
我曾嘗試以下方法來得到它的序列:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(_jsonString, settings);
var jobject = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(_jsonString, new Rootobject());
我曾嘗試以下
- 放在一個默認的構造函數
- 命名爲班級的所有參數的構造函數
- 添加屬性到構造
- 更換板卡列表
- 取出板子屬性
但仍然沒有喜悅。它不會爲我反序列化。
「我收到以下消息」 - 您沒有發佈錯誤消息的文本。當我認爲你的意思是「反序列化」時,你還會使用「序列化」這個術語幾次 - 這是令人困惑的。 – Jason
對不起,試圖一次做一百萬件事。問題已更新。 – Qpirate