C# 从JSON字符串到列表

C# 从JSON字符串到列表,c#,json,.net,.net-core,C#,Json,.net,.net Core,我的jsonResult总是有1+发票(类), 如果它有1张发票,则会给出错误信息 如何更改Json这是System.Text.Json的版本: public static List<int> GetValues(string json) { using JsonDocument doc = JsonDocument.Parse(json); if (doc.RootElement.ValueKind == JsonValueKind.Array) {

我的jsonResult总是有1+发票(类), 如果它有1张发票,则会给出错误信息


如何更改Json这是
System.Text.Json的版本:

public static List<int> GetValues(string json)
{
    using JsonDocument doc = JsonDocument.Parse(json);
    if (doc.RootElement.ValueKind == JsonValueKind.Array)
    {
        return JsonSerializer.Deserialize<List<int>>(json);
    }
    else
    {
        return new List<int>(){ JsonSerializer.Deserialize<int>(json) };
    }
}

检查这将有所帮助,但您可以使用简单的解决方案:检查
jsonResult
是否不是以
[
开头,并更新json,如:
jsonResult=$“[{jsonResult}]”
您使用的JsonDeserialiser是什么?json.NET还是System.Text.json?
public static List<int> GetValues(string json)
{
    using JsonDocument doc = JsonDocument.Parse(json);
    if (doc.RootElement.ValueKind == JsonValueKind.Array)
    {
        return JsonSerializer.Deserialize<List<int>>(json);
    }
    else
    {
        return new List<int>(){ JsonSerializer.Deserialize<int>(json) };
    }
}
var a = GetValues("[1,2,3]"); // List with 3 elements: 1,2,3
var b = GetValues("1");       // List with 1 element: 1