简体   繁体   中英

Deserialize json with data property to a list of objects to what is inside the json array

I try to deserealize it to return to javascript only the data property which is a list.

My controller class which returns the json to javascript:

public ActionResult<IEnumerable> GetCourseThemes(string courseThemesId)
        {
            try
            {
                string jsonResult = _courseService.GetCourseThemes(courseThemesId);

                var ResultObj = JsonConvert.DeserializeObject<List<CourseTheme>>(jsonResult);

                return Ok(ResultObj);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message.ToString());
            }
        }

String json that returns the GetCourseThemes method that the API consumes

{
  "data": [
    {
      "courseThemeId": 3,
      "key": "ESEP",
      "name": "Scrum",
      "registrationDate": "2021-01-29T09:44:05.04",
      "status": true
    }
  ]
}

Error message:

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[Sygno.SE.UI.Core.Entities.CourseTheme]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'data', line 1, position 8. [1]: https://i.stack.imgur.com/VnH6l.png

This is one way to solve your problem:

using Newtonsoft.Json.Linq;
....

var jsonResult = _courseService.GetCourseThemes(courseThemesId);
var jsonObject= JObject.Parse(jsonResult );
var list = jsonObject["data"].ToObjectList<CourseTheme>>();
// or var list =  JsonConvert.DeserializeObject<List<CourseTheme>>(jsonObject["data"].ToString());
return Ok(list );

Your JSON object is a dictionary with a single key ("data"), not an array. The contents of the dictionary entry under that key is the list you are looking for.

Deserializing the JSON object as a dictionary (not as a list), and then accessing the list via its property named "data" will get you the list.

If you can modify _courseService, you could also change the format of the JSON object to be returned as a list rather than a dictionary. Wrapping it in a dictionary with a single key seems pointless, unless it is intended to be an extensible or multi-use object.

You can try to Deserialize jsonResult to JObject ,and Deserialize mydata["data"].ToString() to List<CourseTheme> :

public ActionResult<IEnumerable> GetCourseThemes(string courseThemesId)
        {
            try
            {
                string jsonResult = _courseService.GetCourseThemes(courseThemesId);

                var mydata = JsonConvert.DeserializeObject<JObject>(jsonResult);
                var ResultObj = JsonConvert.DeserializeObject<List<CourseTheme>>(mydata["data"].ToString());

                return Ok(ResultObj);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message.ToString());
            }
        }

result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM