Home > Back-end >  Modifying JSON element of type "dynamic"
Modifying JSON element of type "dynamic"

Time:06-13

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?

CodePudding user response:

  1. Deserialize the json as JObject.
  2. Extract the jObj["values] as JArray.
  3. Update the extracted JArray value and assign to jObj["values"].
JObject jObj = JObject.Parse(json);
JArray values = JArray.Parse(jObj["values"].ToString());
values[0] = 1.0;
jObj["values"] = values;

Sample .NET Fiddle


Or apply the Values property as List<dynamic> type or ArrayList type.

public class Model
{
    [JsonPropertyName("name")]
    public String Name { get; set; }
    [JsonPropertyName("type")]
    public String Type { get; set; }
    [JsonPropertyName("values")]
    public List<dynamic> Values { get; set; }
    // Or
    // public ArrayList Values { get; set; }
}
Model model = JsonConvert.DeserializeObject<Model>(json);
model.Values[0] = 1.0;

Sample .NET Fiddle

  • Related