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:
- Deserialize the json as
JObject
. - Extract the
jObj["values]
asJArray
. - Update the extracted
JArray
value and assign tojObj["values"]
.
JObject jObj = JObject.Parse(json);
JArray values = JArray.Parse(jObj["values"].ToString());
values[0] = 1.0;
jObj["values"] = values;
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;