-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
This issue has been moved from a ticket on Developer Community.
[severity:It's more difficult to complete my work]
Json can be serialized and deserialized with csharp.system.text.json.
However, the current parser imposes huge risks, as it tries to be smart and does do type conversions automatically.
What's needed, a way to enforce as string, or as number, or to disable the automatic conversions.
Cause when we deal with json we often deal with other code languages who are quite clear on the json standards.
We don't need the c# language to ignore those rules ea "123" is a string 123 is a number.
Whats needed an extension JsonDocument.ParseString($""selectedCar": "{selectedCar}""). RootElement;
Or have it a little bit smarter JsonDocument.ParseString(atributename,stringvalue);
This way existing code could still use the auto conversion, or write as string.
something alike below should be in the C# language
using System;
using System.Text.Json;
public static class JsonDocumentExtensions
{
public static void SetStringProperty(this JsonDocument document, string propertyName, string propertyValue)
{
if (document. RootElement.TryGetProperty(propertyName, out JsonElement propertyElement))
{
document. RootElement.Remove(propertyName);
}
document. RootElement.GetOrAddProperty(propertyName). SetValue(propertyValue);
}
private static JsonElement GetOrAddProperty(this JsonElement element, string propertyName)
{
if (element. TryGetProperty(propertyName, out JsonElement propertyElement))
{
return propertyElement;
}
return element. GetOrAddProperty(propertyName, JsonDocument.Parse($"\"{propertyName}\": \"\""). RootElement.GetProperty(propertyName));
}
private static JsonElement GetOrAddProperty(this JsonElement element, string propertyName, JsonElement propertyValue)
{
element. GetOrAddProperty(propertyName);
var jsonDocument = JsonDocument.Parse(propertyValue.GetRawText());
var propertyElement = jsonDocument.RootElement.GetProperty(propertyName);
element. RootElement[propertyName] = propertyElement;
return propertyElement;
}
}So one can do
if (!string. IsNullOrEmpty(carStatus.SelectedCar))
{
jsonDocument.RootElement.SetStringProperty("selectedCar", carStatus.SelectedCar);
}And yes one can say but you have a written extension solution why post this ?... cause it's 2024 the world uses JSON standards !
And if it's as simple as this why not implement it in the language?
Original Comments
Feedback Bot on 2/19/2024, 10:55 PM:
(private comment, text removed)
Original Solutions
(no solutions)