gpt4 book ai didi

c# - 如何创建 C# 类以反序列化以方括号开头和结尾的 JSON 字符串

转载 作者:行者123 更新时间:2023-11-30 15:51:51 29 4
gpt4 key购买 nike

我从 API 接收到一个 JSON 字符串,想将其反序列化为 C# 对象,但无法获得正确的类。

我尝试使用 http://json2csharp.com/ 创建类但它无法解析 JSON,但是 https://jsonlint.com/表示 JSON 有效。

我也试过运行 JsonClassGeneratorLib但那是说

Unable to cast object of type Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject

这似乎是个问题,因为 JSON 包含在 [] 中方括号。我相信这是有效的,但将其放入数组中。我想我在类里面的某个地方需要一个数组。

string Json = @"[""error"",{""code"":2,""msg"":""This API Key is invalid""}]";

var obj = JsonConvert.DeserializeObject<RootObject>(Json);


public class CodeMsg
{
[JsonProperty("code")]
public long Code { get; set; }

[JsonProperty("msg")]
public string Msg { get; set; }
}

public class Result
{
[JsonProperty("error")]
public string String { get; set; }
public CodeMsg cm { get; set; }
}

public class RootObject
{
public Result Result { get; set; }
}

我总是得到错误

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ConsoleApp1.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array

最佳答案

试试这个:

var obj = JsonConvert.DeserializeObject<List<Result>>(Json);

说明:如果 JSON 是数组,则 C# RootObject 必须从 List/IEnumerable 本身派生,或者将其反序列化为类型的列表/数组。

您可以转储您的 RootObject 类。如果您想使用 RootObject 类型,请将其派生自 List。但这不值得麻烦。

关于c# - 如何创建 C# 类以反序列化以方括号开头和结尾的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843443/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com