Primitives.StringValues - 如何将看起来像数组的值反序列化为数组

时间:2016-03-30 00:06:54

标签: c# deserialization query-parameters asp.net-core-1.0

我有一个带有dotnet核心框架的MVC6项目的REST api。 我试图将一些查询参数反序列化为一个数组 我得到以下GET请求:

http://localhost:53384/api/things?sortModel=%7B%22colId%22:%22arrivalDate%22,%22sort%22:%22asc%22%7D&sortModel=%7B%22colId%22:%22arrivalPortCode%22,%22sort%22:%22desc%22%7D

排序模型是一个包含键(列Id)值(“asc”或“desc”)对的数组,我试图将此查询参数转换为List<SortModel>

public class SortModel
{
    public string ColId { get; set; }
    public string Sort { get; set; }
}

在控制器上,我可以使用以下命令提取查询参数:

IReadableStringCollection paramsCollection = Request.Query;

但是我需要这种方法才能工作:

IEnumerable<SortModel> sortModel = GetSortModel(paramsCollection["sortModel");

private IEnumerable<SortModel> GetSortModel(string sortModel)
{
    // the sortModel string looks like this: "{\"colId\":\"arrivalDate\",\"sort\":\"asc\"},{\"colId\":\"arrivalPortCode\",\"sort\":\"desc\"}"
    var deserialized = JsonConvert.DeserializeObject<List<SortModel>>(sortModel); //this throws an exception but the exception itself is null
    return deserialized;
}

请注意,sortModel字符串不包含[]也不包含{},尽管该键的paramsCollection值似乎是Microsoft.Extensions.Primitives.StringValues,其值如下: {{"colId":"arrivalDate","sort":"asc"},{"colId":"arrivalPortCode","sort":"desc"}}

不确定为什么值会被{}包裹而不是[],但这就是在请求中检索它的方式。

1 个答案:

答案 0 :(得分:0)

我通过手动将字符串转换为json数组解决了这个问题,虽然这似乎不是解决这个问题的“自然”方式,所以我很想知道用于反序列化数组查询参数的更好的内置选项

以下是我如何解决它:

private IEnumerable<SortModel> GetSortModel(string sortModel)
{
     if (sortModel == null)
     {
         return Enumerable.Empty<SortModel>();
     }
     string array = $"[{sortModel}]"; 
     var deserialized = JsonConvert.DeserializeObject<List<SortModel>>(array);
     return deserialized;
 }
相关问题