Reputation: 171
I need to remove the nodes from the JSON dynamically in C# without knowing the actual path of the node in josn. Just using the value comes in the query parameter of URL remove the node and and return the json after removing the node.
public IHttpActionResult mockErrorCandidateResponse()
{
HttpContext currentContext = HttpContext.Current;
KeysCollection keys = currentContext.Request.QueryString.Keys;
string key = keys[0];
string node = currentContext.Request.QueryString[key];
//creating the final response
HttpResponseMessage result = new HttpResponseMessage();
result.StatusCode = HttpStatusCode.BadRequest;
string pathToContent = "~/mockCandidateResponse.json"; //relative path to fetch the file
string actualStrContent = null;
if (!String.IsNullOrEmpty(pathToContent))
{
actualStrContent = Util.getResource(pathToContent);
result.Content = new StringContent(actualStrContent, Encoding.UTF8, "application/json");
}
JObject data = JObject.Parse(actualStrContent); //parsing the json dynamically
data.SelectToken(node).Remove();
actualStrContent = data.ToString();
return ResponseMessage(result);
}
Here the sample JSON
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
When I query GET http://basecandidateurl.com?nodename=**GlossDiv** then it should remove everything under the GlossDiv and return
{
"glossary": {
"title": "example glossary"}
}
Anyhelp is apprreciated. Thanks in advance!
Upvotes: 3
Views: 6095
Reputation: 2921
This worked for me:
var json = @"{
'glossary': {
'title': 'example glossary',
'GlossDiv': {
'title': 'S',
'GlossList': {
'GlossEntry': {
'ID': 'SGML',
'SortAs': 'SGML',
'GlossTerm': 'Standard Generalized Markup Language',
'Acronym': 'SGML',
'Abbrev': 'ISO 8879:1986',
'GlossDef': {
'para': 'A meta-markup language, used to create markup languages such as DocBook.',
'GlossSeeAlso': ['GML', 'XML']
},
'GlossSee': 'markup'
}
}
}
}
}";
var nodeToRemove = "GlossDef";
// Step 01: Parse json text
JObject jo = JObject.Parse(json);
// Step 02: Find Token in JSON object
JToken tokenFound = jo.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == nodeToRemove)
.Select(p => ((JProperty)p).Value)
.FirstOrDefault();
// Step 03: if the token was found select it and then remove it
if (tokenFound != null)
{
var token = jo.SelectToken(tokenFound.Path);
token.Parent.Remove();
}
json = jo.ToString();
which returns the json string:
{
"glossary": {
"title": "example glossary"
}
}
I used the Json.Net library which you can nuget into your project by searching for Newtonsoft.Json
Upvotes: 4