0
我從我的服務器得到一個json字符串/對象到我的c#客戶端。解析JSON到一個對象
這是JSON:
[
{"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"},
{"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}]
我試圖將其轉換爲對象的列表,像這樣:
var strJson2 = (JObject)JsonConvert.DeserializeObject(strJson);
:
public IEnumerable<Model.Print> Get()
{
var print = new List<Model.Print>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Shared.URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result;
if (response.IsSuccessStatusCode)
{
var strJson = response.Content.ReadAsStringAsync().Result;
var strJson2 = (JObject)JsonConvert.DeserializeObject(strJson);
List<Model.Print> items = strJson2["data"].Select(x => new Model.Print
{
CompanyRef = (Guid)x["CompanyRef"],
Header = (string)x["Header"],
PrintId = (int)x["PrintId"],
PrintRef = (Guid)x["PrintRef"],
TC = (string)x["TC"]
}).ToList();
}
else
{
evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
}
}
return print;
}
但它在這一行錯誤
這是錯誤:
Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.
JsonConvert.DeserializeObject <列表>(strJson) –
Mate
嗨,這並在使用Raspberry Pi2(Windows 10 IoT作爲操作系統)時不起作用。我忘了添加Raspberry Pi2標籤。 - 對不起 –