user1068636
user1068636

Reputation: 1939

How do you modify JSON content in C#?

I have successfully intercepted an HTTP web request in an IIS7/ASP.NET application and using an HttpModule I have detected the content type is "application/json charset=UTF-8".

I used a Proxy tool to determine what the JSON content looks like.

I am using an HttpModule to intercept this web request and I would like to modify the JSON content.

My question is: how do you extract the JSON content into a JSON object, modify it, and update the original web request with my changes?

For example, suppose the JSON content looks like

{
    "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"
                }
            }
        }
    }
}

Then what i want to do is:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "C H A N G E   1",
                    "SortAs": "C H A N G E  2",
                    "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": ["AAA", "BBB", "CCC"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

I am using C# code to implement the HttpModule.

Upvotes: 1

Views: 219

Answers (1)

Damian
Damian

Reputation: 2852

Using Newtonsoft.Json you can do this:

dynamic json = JObject.Parse("{'glossary':{'title':'example glossary','GlossDiv':{'title':'S','GlossList':{'GlossEntry':{'ID':'C H A N G E   1','SortAs':'C H A N G E  2','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':['AAA','BBB','CCC']},'GlossSee':'markup'}}}}}");

json.glossary.GlossDiv.GlossList.GlossEntry.ID = 1234;
json.glossary.GlossDiv.GlossList.GlossEntry.SortAs = "abcde";

string result = json.ToString();

Upvotes: 2

Related Questions