![](/img/trans.png)
[英]Efficiently get full json string in JsonConverter.ReadJson()
[英]Newtonsoft JSON - How to use the JsonConverter.ReadJson method to convert types when deserializing JSON
我需要幫助了解如何使用JsonConverter.ReadJson方法將任意數量的類型(字符串,布爾值,日期,整數,數組,對象)的值轉換為特定的自定義類型。
例如,我有以下內容;
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;
}
不確定這是否是最好的解決方案,但它確實起到了作用。
您可以在轉換之前測試值類型。 你可以這樣做:
if (reader.TokenType != JsonToken.String)
{
throw new JsonSerializationException();
}
var value = serializer.Deserialize<string>(reader);
既然它是一個對象的基礎,而你只想要字符串,為什么不這樣稱它:
return new MyCustomType(reader.Value.ToString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.