[英]How to handle both a single item and an array for the same property using JSON.net
[英]How to show the decimal value as it is when Deserializing using JSON.NET in Azure APIM?
我正在使用 Azure APIM 策略表達式來聚合多個響應。 我在響應中有一些小數值。 但是在反序列化時,格式已更改,如 output 所示。我想返回輸入中的格式。
輸入
{
"x1": 1.55391E4,
"x2": 2.2173244E5,
"x3": 1.11226E3,
"UpdatedDateTime": "2023-01-17T20:45:51.959+08:00"
}
OUTPUT
{
"x1": 15539.1,
"x2": 221732.44,
"x3": 1112.26,
"UpdatedDateTime": "2023-01-17T20:45:51.959+08:00"
}
預期的
{
"x1": 1.55391E4,
"x2": 2.2173244E5,
"x3": 1.11226E3,
"UpdatedDateTime": "2023-01-17T20:45:51.959+08:00"
}
這是我的小提琴
在此示例中,我保留了帶偏移量的 DateTimeZone。 但我不能做小數字段(x1、x2、x3)。 我只想返回,因為它就像輸入一樣。
請注意,我在策略表達式中編寫此內容,因此我無法創建任何 C# 擴展或輔助方法。
在JToken
層次結構中對decimal
值強制使用科學記數法的一種方法是用適當格式化的JRaw
值替換十進制值的JValue
標記:
var settings = new JsonSerializerSettings
{
// Make sure that FloatParseHandling is consistent with the later check ".Where(v => v.Value is decimal)"
FloatParseHandling = FloatParseHandling.Decimal,
FloatFormatHandling = FloatFormatHandling.DefaultValue,
// Instead of DateParseHandling.DateTimeOffset, you could use DateParseHandling.None to skip DateTime recognition and leave date/time strings unchanged.
DateParseHandling = DateParseHandling.DateTimeOffset,
DateTimeZoneHandling = DateTimeZoneHandling.Unspecified
};
var obj = JsonConvert.DeserializeObject<JObject>(json, settings);
var decimalValues = obj.Descendants().OfType<JValue>().Where(v => v.Value is decimal).ToList();
foreach (var value in decimalValues)
{
value.Replace(new JRaw(((decimal)value.Value).ToString("0.00000E0" /*, System.Globalization.CultureInfo.InvariantCulture */))); // Is System.Globalization.CultureInfo.InvariantCulture available?
}
var newJson = obj.ToString(Formatting.Indented);
結果是
{
"x1": 1.55391E4,
"x2": 2.21732E5,
"x3": 1.11226E3,
"UpdatedDateTime": "2023-01-17T20:45:51.959+08:00"
}
演示小提琴 #1在這里。
筆記:
您的代碼位於 Azure APIM 策略表達式中。 此類表達式中只允許使用非常有限的類型集,如.NET Framework types allowed in policy expressions中所述。 請注意,以下內容不可用:
Newtonsoft.Json.JsonConverter
。Newtonsoft.Json.JsonTextReader
和JsonTextWriter
。System.Text.Json
(全部)。 缺乏創建自定義轉換器的能力是我建議使用JRaw
的原因。
您不能使用 Json.NET 保留原始的十進制格式。當JsonTextReader
遇到浮點數 JSON 數字時,它會將其解析為decimal
或double
精度並丟棄原始的 JSON 字符序列。 因此,僅保留值(以及decimal
情況下的位數)。
另一方面,來自 System.Text.Json 的Utf8JsonReader
確實保留了底層的 JSON 字符序列。 此字符序列被傳遞給JsonElement
和JsonNode
,它們也保留原始字符序列並呈現它的只讀(或可編輯)視圖。 因此,如果 Azure APIM 策略表達式得到增強以允許 System.Text.Json,您將能夠更輕松地保留原始的 JSON 十進制格式。
演示小提琴 #2在這里。
如果您想保留所有日期和時間字符串值不變,而不是DateParseHandling.DateTimeOffset
,您可以使用DateParseHandling.None
完全禁用 DateTime 識別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.