gpt4 book ai didi

c# - 当值可以是对象或空数组时反序列化 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:12 25 4
gpt4 key购买 nike

我正在使用 VK API。有时服务器可以返回空数组而不是对象,例如:

personal: [] //when it is empty

personal: {
religion: 'Нет',
smoking: 1,
alcohol: 4
} //when not empty.

我正在使用 JsonConvert.DeserializeObject 反序列化大部分 json,而这部分 json 则使用

MainObject = ((MainObject["response"].GetObject())["user"].GetObject())["personal"].GetObject();
try
{
Convert.ToByte(MainObject["political"].GetNumber();
}
catch {}

但是当它处理大量异常时,它会使应用程序运行缓慢。刚才我意识到这里还有一些字段可能会在空时返回数组。我只是不知道如何快速而清晰地制作它。有什么建议吗?

我的反序列化类(字段为空时不起作用):

     public class User
{
//some other fields...
public Personal personal { get; set; }
//some other fields...
}
public class Personal
{
public byte political { get; set; }
public string[] langs { get; set; }
public string religion { get; set; }
public string inspired_by { get; set; }
public byte people_main { get; set; }
public byte life_main { get; set; }
public byte smoking { get; set; }
public byte alcohol { get; set; }
}

另一个想法(不为空时不起作用):

public List<Personal> personal { get; set; }

最佳答案

你可以做一个JsonConverter如下所示,它查找指定类型的对象或空数组。如果是对象,则反序列化该对象。如果是空数组,则返回 null:

public class JsonSingleOrEmptyArrayConverter<T> : JsonConverter where T : class
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}

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

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType);
if (!(contract is Newtonsoft.Json.Serialization.JsonObjectContract || contract is Newtonsoft.Json.Serialization.JsonDictionaryContract))
{
throw new JsonSerializationException(string.Format("Unsupported objectType {0} at {1}.", objectType, reader.Path));
}

switch (reader.SkipComments().TokenType)
{
case JsonToken.StartArray:
{
int count = 0;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
case JsonToken.EndArray:
return existingValue;
default:
{
count++;
if (count > 1)
throw new JsonSerializationException(string.Format("Too many objects at path {0}.", reader.Path));
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
}
break;
}
}
// Should not come here.
throw new JsonSerializationException(string.Format("Unclosed array at path {0}.", reader.Path));
}

case JsonToken.Null:
return null;

case JsonToken.StartObject:
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
return existingValue;

default:
throw new InvalidOperationException("Unexpected token type " + reader.TokenType.ToString());
}
}

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

public static partial class JsonExtensions
{
public static JsonReader SkipComments(this JsonReader reader)
{
while (reader.TokenType == JsonToken.Comment && reader.Read())
;
return reader;
}
}

然后像这样使用它:

public class User
{
//some other fields...
[JsonConverter(typeof(JsonSingleOrEmptyArrayConverter<Personal>))]
public Personal personal { get; set; }
//some other fields...
}

您现在应该能够将用户反序列化到您的 User 类中。

注意事项:

工作示例 .Net fiddles herehere .

关于c# - 当值可以是对象或空数组时反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303628/

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