Cast object of (string, multidimensional-array) as JSON result in C# Dotnet 5.0

isl*_*mdi 5 c# asp.net-core asp.net5

I have a controller that has the following structure/classes:

// model
public class Result
{
    public string Document { get; set; } = "";

    public int[,] Segments { get; set; } = new int[,] { };
}

// controller
public class SearchController : ControllerBase {
    [HttpGet]
    [Route("/api/v1/[controller]")]
    [Produces("application/json")]
    public IActionResult Search(//metadata list)
    {
      try {
            Result result = <service-call-returning Result object>;
            return Ok(result);
      } catch (Exception e) {
            return BadRequest("bad");
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

It seems that it's not able to serialize the Result object, I am getting the following exception:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]

An unhandled exception has occurred while executing the request.

System.NotSupportedException: The type 'System.Int32[,]' is not supported.

at System.Text.Json.ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(Type propertyType)
at System.Text.Json.Serialization.Converters.IEnumerableConverterFactory.CreateConverter(Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverterFactory.GetConverterInternal(Type typeToConvert, JsonSerializerOptions options)
at System.Text.Json.JsonSerializerOptions.GetConverter(Type typeToConvert)

How do I go about serializing an object with (string, multidimensional array)? Also I have a react app that expects a result, the string is going to be serialized as well (has \n\n \r ....), is it the job for the client app to deserialize it or I need to find a way to return the JSON object as it is non-serialized?

N P*_*iro 5

其实问题出在你的int[,]类型上。int[][]例如,您可以将多维数组替换为。

事实上,下面的代码片段引发了与您类似的异常。

using System;
using System.Text.Json;
                    
public class Program
{
    public static void Main()
    {
        var example = new int[,]  { { 99, 98, 92 }, { 97, 95, 45 } };
        Console.WriteLine(JsonSerializer.Serialize(example));
    }
}
Run Code Online (Sandbox Code Playgroud)

例外情况:

Unhandled exception. System.NotSupportedException: The type 'System.Int32[,]' is not supported.
   at System.Text.Json.ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(Type propertyType)
   ...
Run Code Online (Sandbox Code Playgroud)

但是,如果将example声明替换为int[][],那么我们可以得到:

var example = new int[][]  { new int[] { 99, 98, 92 },  new int[] { 97, 95, 45 }, };
Run Code Online (Sandbox Code Playgroud)

这可以序列化为:

[[99,98,92],[97,95,45]]
Run Code Online (Sandbox Code Playgroud)


Fra*_*rdo 4

根据How to serialize and deserialize (marshal and unmarshal) JSON in .NET,不支持多维数组System.Text.Json

支持的类型包括:

  • 映射到 JavaScript 原语的 .NET 原语,例如数字类型、字符串和布尔值。
  • 用户定义的普通旧 CLR 对象 (POCO)。
  • 一维和锯齿状数组 (T[][])。
  • 来自以下命名空间的集合和字典。
    • 系统.集合
    • 系统.集合.通用
    • 系统.集合.不可变
    • 系统.集合.并发
    • 系统.集合.专业化
    • 系统.集合.对象模型

因此,我认为您可以做的一个选择是将多维数组转换为列表:

public class Result
{
    public string Document { get; set; } = "";

    public IList<IList<int>> Segments { get; set; } = new List<IList<int>>();
}
Run Code Online (Sandbox Code Playgroud)

或者使用锯齿状数组:

public class Result
{
    public string Document { get; set; } = "";

    public int[][] Segments { get; set; } = new int[][] { };
}
Run Code Online (Sandbox Code Playgroud)

更新

如果您知道数组的维度,另一种选择是仅为您的 JSON 属性编写自定义 getter/setter。此示例假设多维数组的第二维为 2。

public class Result
{
    public string Document { get; set; } = "";

    [JsonIgnore]
    public int[,] Segments { get; set; } = new int[,] { };

    [JsonPropertyName("segments")]
    public IList<IList<int>> JsonSegments
    {
        get
        {
            var value = new List<IList<int>>();
            for (int i = 0; i < Segments.Length / 2; i++)
            {
                value.Add(new List<int> { Segments[i, 0], Segments[i, 1] });
            }
            return value;
        }
        set
        {
            var dimension = value.Count;
            Segments = new int[dimension,2];
            var index = 0;
            foreach (var item in value)
            {
                if (item.Count == 2)
                {
                    Segments[index, 0] = item[0];
                    Segments[index, 1] = item[1];
                    index += 1;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)