There is a large JSON file (about a thousand lines). The task is to update existing JProperties, or add new JProperties in a specific location in the structure. The location of the new texts are based on the JToken.Path property. For example, this is the start of the JSON:
"JonSnow": {
"Direwolf": {
"Name": "Ghost",
"Color": "White",
}
}
"DanaerysTargaryen": {
"Dragons": {
"Dragon1": {
"Name": "Drogon",
}
}
"Hair": {
"Color": "White"
}
}
Now the JSON must be updated using a given list of JToken paths and the corresponding values.
The first possibility is, the JProperty corresponding to the path might already exist, in which case the value needs to be updated. I am already successfully implementing this with JToken.Replace()
.
The second possibility is, the JProperty does not exist yet and needs to be added. For example, I need to add "DanaerysTargaryen.Dragons.Dragon1.Color"
with the value "Black"
.
I know I can use the JSON.Net Add()
method, but to use this only the final child token of the path can be missing from the JSON. For example, I can use
JObject ObjToUpdate= JObject.Parse(jsonText);
JObject Dragon = ObjToUpdate["DanaerysTargaryen"]["Dragons"]["Dragon1"] as JObject;
Dragon.Add("Color", "Black"));
But what about if I need to add "JonSnow.Weapon.Type"
with the value "Longsword"
? Because "Weapon"
does not exist yet as a JProperty, and it needs to be added along with "Type" : "Longsword"
. With each path, it is unknown how much of the path already exists in the JSON. How can this be parameterised?
// from outside source: Dictionary<string, string> PathBasedDict
// key: Jtoken.Path (example: "JonSnow.Weapon.Type")
// value: new text to be added (example: "Longsword")
foreach(KeyValuePair entry in PathBasedDict)
{
string path = entry.Key;
string newText = entry.Value;
if (ObjToUpdate.SelectToken(path) != null)
{ ObjToUpdate.SelectToken(path).Replace(newText); }
else AddToJson(path, newText);
}
What should AddToJson()
look like? Iterating through the entire path and checking each possible JProperty to see if it exists, and then adding the rest underneath, seems very cumbersome. Is there a better way to do this? Any Json.NET tricks I am unaware of? I am not even sure how the iteration could be parameterised.
See Question&Answers more detail:
os