3

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!

0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

It worked in this case but cannot handle all the cases properly. Thanks!
Is that because you dont know what the root node is named? Let me update my answer so that it extracts the root node name first.
Yes it worked only the node is direct child but not for other like some one query for the GlossDef it will not work then
Think I have cracked it.. I will update answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.