我正在使用它來反序列化來自 Api 的 Json 回應。
var apiResponse = await GetAsync<MyResponseModel>(request);
在我的回應模型中,有一個 int 屬性,但 api 出于某種原因將其格式化為浮點數。所以它看起來像這樣:
{
"Quantity": 6.000
}
現在我用這個技巧決議它:
[JsonProperty("Quantity")]
private float QuantityFloat {
set => Quantity = IsInt(value) ? (int) value: throw new ArgumentException("Tried to parse number to Quantity that is not an int.");
}
public int Quantity { get; set; }
private static bool IsInt(float value)
{
var x = (int) value;
var temp2 = value - x;
return temp2 <= 0;
}
我的 linter 現在抱怨:“只有 setter 的屬性令人困惑和違反直覺。相反,如果可能,應該添加屬性 getter,或者應該用 setter 方法替換該屬性。” 所以我問自己是否有更好更優雅的方法來做到這一點。
uj5u.com熱心網友回復:
我建議創建一個JsonConverter<int>可以處理整數和十進制格式的值:
(此解決方案適用于 System.Text.Json)
public class IntConverter : JsonConverter<int>
{
public override int Read(ref Utf8JsonReader reader, System.Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TryGetInt32(out var intVal))
{
return intVal;
}
// customize this part as necessary to satisfactorily deserialize
// the float value as int, or throw exception, etc.
float floatValue = reader.GetSingle();
return (int)floatValue;
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
然后你可以裝飾你的屬性,[JsonConverter(typeof(IntConverter))]這將導致在序列化期間使用轉換器:
public class Model
{
[JsonConverter(typeof(IntConverter))]
public int Quantity { get; set; }
}
像這樣處理它消除了對任何額外屬性的需求,從而簡化了您的解決方案。如果您必須在多個地方處理此類場景,則尤其如此。
網上試試
JSON.NET 解決方案:
public class IntConverter : JsonConverter<int>
{
public override int ReadJson(JsonReader reader, Type objectType, int existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Float)
{
// customize this part as necessary to satisfactorily deserialize
// the float value as int, or throw exception, etc.
double value = (double)reader.Value;
return (int)value;
}
long intVal = (long)reader.Value;
return (int)intVal;
}
public override void WriteJson(JsonWriter writer, int value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
使用以下模型:
public class Model
{
[JsonConverter(typeof(IntConverter))]
public int Quantity { get; set; }
}
網上試試
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366976.html
上一篇:將串列分組和排序到地圖中
