вот мой Json Объектобъект Json к модели MVC
{
"id":5,
"url":"http://localhost:8001/api/courses/5",
"name":"Professional Experience II",
"duration":"5.0",
"description":"The course will talk in depth about every thing",
"tutor": {
"id":2,
"email":"[email protected]",
"userName":"TA",
"firstName":"T",
"lastName":"A",
"gender":0
},
"subject":
{
"id":2,
"name":"Science"
}
}
и моя модель здесь
public class CourseModel
{
public int Id { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public double Duration { get; set; }
public string Description { get; set; }
public TutorModel Tutor { get; set; }
public SubjectModel Subject { get; set; }
}
и это, как я получаю этот объект. Я могу получить JSONObject, но не в состоянии Deserialize его в соответствующей модель
string url = "http://localhost:8001/api/courses/5";
HttpResponseMessage responseMessage = await client.GetAsync(url);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<List<CourseModel>>(responseData);
return View(data);
}
return View("Error:);
Ошибки я получаю
Не может десериализации текущего объекта JSON (например, { «имя»: "значение "}) в тип 'System.Collections.Generic.List`1 [Learning.Web.Models.CourseModel]' , потому что для этого требуется массив JSON (например, [1,2,3]) для десериализации . Чтобы исправить эту ошибку, либо измените JSON на массив JSON (например, [1,2,3]), либо измените десериализованный тип, чтобы он был обычным типом .NET (например, не примитивным типом типа, а не набором типа типа или списка), который можно десериализовать из объекта JSON . JsonObjectAttribute также можно добавить к типу, чтобы заставить его десериализоваться из объекта JSON. Путь «Идентификатор», строка 1, позиция 6.
Я использую WebAPI и я не уверен, что я делаю неправильно здесь .. Любая помощь будет оценена
Обновлено:
Based на Shyju и Хабиб ответить на это будет работать, если я десериализации его в одном экземпляре, но если я изменить URL-адрес для
string url = "http://localhost:8001/api/courses";
и десериализации его в список, я получаю ту же ошибку, вот объект JSON
{
"totalCount":32,
"totalPages":4,
"prevPageLink":"",
"nextPageLink":"http://localhost:8001/api/courses?page=1&pageSize=10",
"results":[
{
"id":1,
"url":"http://localhost:8001/api/courses/1",
"name":"History Teaching Methods 1",
"duration":3.0,
"description":"The course will talk in depth about: History Teaching Methods 1",
"tutor":{
"id":1,
"email":"[email protected]",
"userName":"A,
"firstName":"A",
"lastName":"J",
"gender":0
},
"subject":{
"id":1,
"name":"History"
}
},
{
"id":2,
"url":"http://localhost:8001/api/courses/2",
"name":"History Teaching Methods 2",
"duration":5.0,
"description":"The course will talk in depth about: History Teaching Methods 2",
"tutor":{
"id":1,
"email":"[email protected]",
"userName":"AJo",
"firstName":"A",
"lastName":"Jo",
"gender":0
},
"subject":{
"id":1,
"name":"History"
}
},
{
"id":3,
"url":"http://localhost:8001/api/courses/3",
"name":"History Teaching Methods 3",
"duration":5.0,
"description":"The course will talk in depth about: History Teaching Methods 3",
"tutor":{
"id":1,
"email":"[email protected]",
"userName":"A",
"firstName":"A",
"lastName":"J",
"gender":0
},
"subject":{
"id":1,
"name":"History"
}
},
{
"id":4,
"url":"http://localhost:8001/api/courses/4",
"name":"Professional Experience 1 (Mathematics/Science)",
"duration":5.0,
"description":"The course will talk in depth about: Professional Experience 1 (Mathematics/Science)",
"tutor":{
"id":2,
"email":"[email protected]",
"userName":"T",
"firstName":"T",
"lastName":"A",
"gender":0
},
"subject":{
"id":2,
"name":"Science"
}
},
{
"id":5,
"url":"http://localhost:8001/api/courses/5",
"name":"Professional Experience 2 (Mathematics/Science)",
"duration":5.0,
"description":"The course will talk in depth about: Professional Experience 2 (Mathematics/Science)",
"tutor":{
"id":2,
"email":"[email protected]",
"userName":"T",
"firstName":"T",
"lastName":"A",
"gender":0
},
"subject":{
"id":2,
"name":"Science"
}
},
{
"id":6,
"url":"http://localhost:8001/api/courses/6",
"name":"Professional Experience 3 (Mathematics/Science)",
"duration":5.0,
"description":"The course will talk in depth about: Professional Experience 3 (Mathematics/Science)",
"tutor":{
"id":2,
"email":"[email protected]",
"userName":"T",
"firstName":"T",
"lastName":"A",
"gender":0
},
"subject":{
"id":2,
"name":"Science"
}
},
{
"id":7,
"url":"http://localhost:8001/api/courses/7",
"name":"Geography Teaching Methods 1",
"duration":5.0,
"description":"The course will talk in depth about: Geography Teaching Methods 1",
"tutor":{
"id":3,
"email":"[email protected]",
"userName":"Ti",
"firstName":"T",
"lastName":"W",
"gender":0
},
"subject":{
"id":3,
"name":"Geography"
}
},
{
"id":8,
"url":"http://localhost:8001/api/courses/8",
"name":"Geography Teaching Methods 2",
"duration":5.0,
"description":"The course will talk in depth about: Geography Teaching Methods 2",
"tutor":{
"id":3,
"email":"[email protected]",
"userName":"f",
"firstName":"f",
"lastName":"f",
"gender":0
},
"subject":{
"id":3,
"name":"Geography"
}
},
{
"id":9,
"url":"http://localhost:8001/api/courses/9",
"name":"Geography Teaching Methods 3",
"duration":5.0,
"description":"The course will talk in depth about: Geography Teaching Methods 3",
"tutor":{
"id":3,
"email":"[email protected]",
"userName":"s",
"firstName":"s",
"lastName":"s",
"gender":0
},
"subject":{
"id":3,
"name":"Geography"
}
},
{
"id":10,
"url":"http://localhost:8001/api/courses/10",
"name":"English Education 1",
"duration":5.0,
"description":"The course will talk in depth about: English Education 1",
"tutor":{
"id":4,
"email":"[email protected]",
"userName":"g",
"firstName":"g",
"lastName":"g",
"gender":0
},
"subject":{
"id":4,
"name":"English"
}
}
]
}
Это работает для одного экземпляра .. но если я изменяю URL-адрес на строку url = "http: // localhost: 8001/api/courses"; и десериализовать его в List, я получаю такую же ошибку .. любая идея? – Angloos
, потому что ваши данные json для одного экземпляра, а не из массива из них. – Shyju
если я не использую параметр i.e.5 Я получаю другой объект Json, мне также нужно отобразить другой объект Json? – Angloos