gpt4 book ai didi

c# - Newtonsoft JSON - 反序列化JSON时如何使用JsonConverter.ReadJson方法进行类型转换

转载 作者:可可西里 更新时间:2023-11-01 08:55:06 25 4
gpt4 key购买 nike

我需要帮助了解如何使用 JsonConverter.ReadJson 方法将任意数量的类型(字符串、 bool 值、日期、整数、数组、对象)的值转换为特定的自定义类型。

例如我有以下;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
//where reader.Value could be a string, boolean, Date, int, array, object
//and in this example the value of reader.Value is a string
return new MyCustomType(reader.Value);
}

但这会产生错误;

Compilation error (line 115, col 36): Argument 1: cannot convert from 'object' to 'string'

我对 C# 有点陌生,只是需要帮助才能完成这项工作。

最佳答案

终于搞定了;

public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
MyCustomType myCustomType = new MyCustomType();//for null values

if (reader.TokenType != JsonToken.Null)
{
if (reader.TokenType == JsonToken.StartArray)
{
JToken token = JToken.Load(reader);
List<string> items = token.ToObject<List<string>>();
myCustomType = new MyCustomType(items);
}
else
{
JValue jValue = new JValue(reader.Value);
switch (reader.TokenType)
{
case JsonToken.String:
myCustomType = new MyCustomType((string)jValue);
break;
case JsonToken.Date:
myCustomType = new MyCustomType((DateTime)jValue);
break;
case JsonToken.Boolean:
myCustomType = new MyCustomType((bool)jValue);
break;
case JsonToken.Integer:
int i = (int)jValue;
myCustomType = new MyCustomType(i);
break;
default:
Console.WriteLine("Default case");
Console.WriteLine(reader.TokenType.ToString());
break;
}
}
}
return myCustomType;
}

不确定这是否是最佳解决方案,但它可以完成工作。

关于c# - Newtonsoft JSON - 反序列化JSON时如何使用JsonConverter.ReadJson方法进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586737/

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