首页 > 解决方案 > 反序列化对象数组:无法将 JSON 值转换为 System.String[]

问题描述

无法使用 JSON.Net 访问数组内的对象

public class VoskReturnArray
{
  public string[] result { get; set; }
  public string text { get; set; }
}
    
var voskArray = JsonSerializer.Deserialize<VoskReturnArray>(rec.Result());

Console.WriteLine(voskArray.text); // Works fine
Console.WriteLine(voskArray.result); // Throws an exception

试过了<List<VoskReturnArray>>,但text不会出现。

我在这里想念什么?

数据:

{
  "result" : [{
      "conf" : 0.228337,
      "end" : 0.141508,
      "start" : 0.060000,
      "word" : "one"
    }, {
      "conf" : 1.000000,
      "end" : 0.390000,
      "start" : 0.141508,
      "word" : "hundred"
    }, {
      "conf" : 1.000000,
      "end" : 1.080000,
      "start" : 0.390000,
      "word" : "employees"
    }],
  "text" : "one hundred employees that's where it is you know they had the same problems are those five employees companies but they have the money to pay to fix them"
}

标签: c#json.net

解决方案


您的数据显示result为对象数组,而模型中的result属性VoskReturnArray是字符串数组。它应该是这些对象的模型类型的数组。所以而不是:

public string[] result { get; set; }

你会想要这样的东西:

public ResultItem[] result { get; set; }

...

public class ResultItem
{
    public decimal conf { get; set; }
    public decimal end { get; set; }

    // etc
}

推荐阅读