dimanche 12 juin 2022

Modifying JSON element of type "dynamic"

I am trying to deserialize some JSON data, make a modification to a small part of the data, and re-serialize back into JSON format.

The JSON data looks something like this:

{
    "name": "...",
    "type": "...",
    "values": [0, 1, "apple", ...],
    ...
}

values is a mixed-type array with an unknown number of elements, and as such I use the dynamic type for its C# model:

public class Model
{
    [JsonPropertyName("name")]
    public String Name { get; set; }
    [JsonPropertyName("type")]
    public String Type { get; set; }
    [JsonPropertyName("values")]
    public dynamic Values { get; set; }
    ...
}

Deserializing the object is simple:

Value = model.Values[0].GetDouble();

However, I am unable to write to it because dynamic is apparently read only:

model.Values[0] = 1.0;

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Property or indexer 'System.Text.Json.JsonElement.this[int]' cannot be assigned to -- it is read only'

How can I accomplish this?





Aucun commentaire:

Enregistrer un commentaire