Как десериализовать вложенный JSON и привязать его к модели для представления в виде - PullRequest
0 голосов
/ 04 мая 2019

Я звоню RestApi, который дает мне вложенный JSON в ответ. Я должен обработать этот вложенный Json и представлять в том же частичном представлении. Я поделюсь своей моделью, видом и кодом контроллера.

Я создал контроллер для вызова API и сбора данных. Его заполняющий корневой класс, но не заполняющий дочерний класс

JSON:

{
    "id": 98,
    "title": "all numbers",
    "clues_count": 5,
    "clues": [
        {
            "id": 602,
            "answer": "<i>Eight</i>",
            "question": "It was \"enough\" for Dick van Patten",
            "value": 100,
            "airdate": "1984-09-14T12:00:00.000Z",
            "category_id": 98,
            "game_id": null,
            "invalid_count": null
        },
        {
            "id": 608,
            "answer": "16",
            "question": "A teen's \"sweet\" age",
            "value": 200,
            "airdate": "1984-09-14T12:00:00.000Z",
            "category_id": 98,
            "game_id": null,
            "invalid_count": null
        },
        {
            "id": 614,
            "answer": "<i>The Grapes of Wrath</i>",
            "question": "",
            "value": null,
            "airdate": "1984-09-14T12:00:00.000Z",
            "category_id": 98,
            "game_id": null,
            "invalid_count": null
        },
        {
            "id": 620,
            "answer": "Nathaniel Hawthorne",
            "question": "",
            "value": null,
            "airdate": "1984-09-14T12:00:00.000Z",
            "category_id": 98,
            "game_id": null,
            "invalid_count": null
        },
        {
            "id": 626,
            "answer": "F. Scott Fitzgerald",
            "question": "",
            "value": null,
            "airdate": "1984-09-14T12:00:00.000Z",
            "category_id": 98,
            "game_id": null,
            "invalid_count": 1
        }
    ]
}

Модель:

public class Clue
{
    public int id { get; set; }
    public string answer { get; set; }
    public string question { get; set; }
    public int? value { get; set; }
    public DateTime airdate { get; set; }
    public int category_id { get; set; }
    public object game_id { get; set; }
    public int? invalid_count { get; set; }
}

public class RootObject
{
    public int id { get; set; }
    public string title { get; set; }
    public int clues_count { get; set; }
    public List<Clue> clues { get; set; }
}

Контроллер

   public async Task<ActionResult> Category( int id)
        {
            //  List<Category> clueInfo = new List<Category>();
            List<RootObject> cluess = new List<RootObject>();
            RootObject category = new RootObject();

            category.clueslist  = new List<Clues>();







            using (var client = new HttpClient())
            {
                //Passing service base url  
                client.BaseAddress = new Uri(Baseurl);

                client.DefaultRequestHeaders.Clear();
                //Define request data format  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api/category?id=" + id);
                Debug.WriteLine("My debug string here");

                //Checking the response is successful or not which is sent using HttpClient  
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api   
                    var ClueResponse = Res.Content.ReadAsStringAsync().Result;




                    //Deserializing the response recieved from web api and storing into the Employee list  
                     category = JsonConvert.DeserializeObject<RootObject>(ClueResponse);

                }






               // return View();
                return PartialView("Category", cluess);
            }

Результат на просмотре

title 
clues_count 

dining out 
20
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...