gpt4 book ai didi

c# - 强制将空 JSON 数组转换为字典类型

转载 作者:行者123 更新时间:2023-11-30 14:54:53 26 4
gpt4 key购买 nike

问题是,json_encode() PHP 中的函数为读取其输出的工具留下了歧义。在 PHP 中,列表和字典都是相同类型的 array .

echo json_encode([]); // []
echo json_encode(["5" => "something"]); // {"5": "something"}

在 JSON.NET 中,我想同时强制 []{"5": "something"}转换为 Dictionary<string, string>类型。但是它识别[]作为 Dictionary 的禁止结构并抛出异常。

我能否快速将空的 JSON 数组置为空或强制它们转换为空的字典类型?

最终解决方案

我修改了已接受的答案,使其通用并可重复用于其他类型。

public class DictionaryOrEmptyArrayConverter<T,F> : JsonConverter
{
public override bool CanWrite { get { return false; } }
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<T, F>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.StartArray:
reader.Read();
if (reader.TokenType == JsonToken.EndArray)
return new Dictionary<T, F>();
else
throw new JsonSerializationException("Non-empty JSON array does not make a valid Dictionary!");
case JsonToken.Null:
return null;
case JsonToken.StartObject:
var tw = new System.IO.StringWriter();
var writer = new JsonTextWriter(tw);
writer.WriteStartObject();
int initialDepth = reader.Depth;
while (reader.Read() && reader.Depth > initialDepth)
{
writer.WriteToken(reader);
}
writer.WriteEndObject();
writer.Flush();
return JsonConvert.DeserializeObject<Dictionary<T, F>>(tw.ToString());
default:
throw new JsonSerializationException("Unexpected token!");
}
}

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

您应该将它与您的 JSON 对象一起使用,如下例所示:

public class Company
{
public string industry_name { get; set; }

[JsonConverter(typeof(DictionaryOrEmptyArrayConverter<int, Upgrade>))]
public Dictionary<int, Upgrade> upgrades { get; set; }
}

public class Upgrade
{
public int level { get; set; }
}

它允许您使用 DeserializeObject 快速将 JSON 字符串转换为对象方法:

var result = JsonConvert.DeserializeObject<Company>(jsonString);

最佳答案

您可以使用自定义 JsonConverter 来完成,尽管我认为这个解决方案还有一些不足之处:

    private class DictionaryConverter : JsonConverter
{
public override bool CanWrite { get { return false; } }
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, string>);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
reader.Read();
if (reader.TokenType == JsonToken.EndArray)
return new Dictionary<string, string>();
else
throw new JsonSerializationException("Non-empty JSON array does not make a valid Dictionary!");
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
else if (reader.TokenType == JsonToken.StartObject)
{
Dictionary<string, string> ret = new Dictionary<string, string>();
reader.Read();
while (reader.TokenType != JsonToken.EndObject)
{
if (reader.TokenType != JsonToken.PropertyName)
throw new JsonSerializationException("Unexpected token!");
string key = (string)reader.Value;
reader.Read();
if (reader.TokenType != JsonToken.String)
throw new JsonSerializationException("Unexpected token!");
string value = (string)reader.Value;
ret.Add(key, value);
reader.Read();
}
return ret;
}
else
{
throw new JsonSerializationException("Unexpected token!");
}
}

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

https://dotnetfiddle.net/zzlzH4 查看此代码的运行情况

关于c# - 强制将空 JSON 数组转换为字典类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725138/

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