Search code examples
c#jsonappendchild

Manipulating JSON String in C# without Object


I have JSON String which I am reading from file. I don't have the source of the JSON Object. So I can't call JsonConvert.DeserializeObject.

However I want check if the JSON String has specific structure, if yes, append some string or If not append the structure.

allmodules {
    feature: 'test-a'
}

submodules {
    //some data
}

Assume if there's not allmodules, I would like to append my structure

allmodules {
    feature: 'debug-a'
}

If it's already available, just append feature: 'debug-a'

And so on I have some custom work to do. Is there any efficient way to do this without breaking JSON format. Most of the questions regarding String to Object de-serialization, however as I mentioned I don't have original Object, and can't do that.


Solution

  • You can do this using JObject and doing a little manual parsing. It could look something like this:

    public string AppendAllModules(string json)
    {
        var obj = JObject.Parse(json);
        JToken token;
        if (obj.TryGetValue("allmodules", out token))
            return json;
    
        obj.Add(new JProperty("allmodules", new JObject(new JProperty("feature", "test-a"))));
        return obj.ToString();
    }
    

    Given:

    {
        "submodules": {
            "name": "yuval"
        }
    }
    

    Would yield:

    {
      "submodules": {
        "name": "yuval"
      },
      "allmodules": {
        "feature": "test-a"
      }
    }