I am editing a serialized string becuase when deserilized it gives a parse error.
so from a long Serialized string I want to edit "myVar\": \"0.2 mm"
with "myVar\": \"0.2"
if I use the follwoing code it works
string NewString = Serializedstring.Replace($"myVar\": \"0.2 mm", $"myVar\": \"0.2")
but my 0.2
is a varible that may change with every occurance. so all I want is to remove mm
from the string "myVar\": \"0.2 mm"
If your JSON is coming in with two different formats, rather than trying to hack the JSON string into something usable, it is much safer to use a custom JsonConverter
. For example:
public class MillimetreJsonConverter : JsonConverter<double>
{
public override double Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
// First try to get a double, if it works then simply return it
if(reader.TryGetDouble(out var val))
{
return val;
}
// Otherwise we get the string value e.g. "0.2 mm" and
// do some simple string manipulation on it
var value = reader.GetString()!;
value = value.Replace(" mm", "");
if(double.TryParse(value, out var result))
{
return result;
}
// If we get here, perhaps we should throw an exception?
return 0;
}
public override void Write(Utf8JsonWriter writer, double value,
JsonSerializerOptions options)
{
// You can fill this in if you need it
throw new NotImplementedException();
}
}
Now you can modify the class to deserialise into, assuming your JSON looks like this {"myVar": "0.2 mm"}
,:
public class Foo
{
[JsonConverter(typeof(MillimetreJsonConverter))]
public double myVar { get; set; }
}
Finally, it's simple to deserialise:
var foo = JsonSerializer.Deserialize<Foo>(json);