gpt4 book ai didi

c# - 处理 JSON 单个对象和数组

转载 作者:太空狗 更新时间:2023-10-29 18:26:30 30 4
gpt4 key购买 nike

我正在使用 Newtonsoft.Json 处理返回给我的一些 JSON 数据。根据我的要求,我可以取回如下内容:

{
"TotalRecords":2,
"Result":
[
{
"Id":24379,
"AccountName":"foo"
},
{
"Id":37209,
"AccountName":"bar"
}
],
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}

{
"Result":
{
"Id":24379,
"AccountName":"foo"
},
"ResponseCode":0,
"Status":"OK",
"Error":"None"
}

所以有时“Result”是一组结果,或者“Result”可能是单个响应。

我试过使用来自 How to handle both a single item and an array for the same property using JSON.net 的答案但我仍然遇到错误。

特别是我得到了一个

Newtonsoft.json.jsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List'...

自定义转换器看起来像:

public class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objecType)
{
return (objecType == typeof(List<T>));
}

public override object ReadJson(JsonReader reader, Type objecType, object existingValue,
JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

我的响应类看起来像

public class TestResponse
{
[JsonProperty("Result")]
[JsonConverter(typeof(SingleOrArrayConverter<string>))]
public List<DeserializedResult> Result { get; set; }
}
public class DeserializedResult
{
public string Id { get; set; }
public string AccountName { get; set; }
}

最后我的请求看起来像

List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);

最佳答案

您的代码很好,只需要进行一些类型调整。

这一行

List<TestResponse> list = JsonConvert.DeserializeObject<List<TestResponse>>(response.Content);

需要像这样,因为您的回复是 object , 不是 List .

TestResponse list = JsonConvert.DeserializeObject<TestResponse>(response);

然后是您的自定义反序列化器属性:

[JsonConverter(typeof(SingleOrArrayConverter<string>))]

需要成为:

[JsonConverter(typeof(SingleOrArrayConverter<DeserializedResult>))]

因为你的 Result对象不是 stringstring 的数组s,它可以是 DeserializedResult 的数组s 或 DeserializedResult .

关于c# - 处理 JSON 单个对象和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44100383/

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