我有一个WebApi返回以下JSON,我试图反序列化到下面的对象
JSON OBJECT
{
"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#Classes
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,我通过nuget安装了JSON.net(10.0.1),但是可移植库连接到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());
我试过以下
但仍然没有快乐。它不会为我反序列化。
答案 0 :(得分:0)
我认为你必须修改这个
public class Board
{
public int companyId { get; set; }
public string companyName { get; set; }
public int? companyOffLimits { get; set; }
public object restrictionCategoryId { get; set; }
**public Board(){}**
}
也在其他班级
或者也改变
public Board[] boards { get; set; }
到
public List<Board> boards { get; set; }
...试