One of the recent questions that came up in SO which fascinated me was how do one filter a Json string by removing properties from Json, which is of a particular Type. For example, consider the following Json.
{ 'widget': { 'debug': 'on', 'window': { 'title': 'Sample Widget', 'name': 'main_window', 'width': 500, 'height': 500 }, 'image': { 'src': 'Images/Sun.png', 'name': 'sun1', 'hOffset': 250, 'vOffset': 250, 'alignment': 'center' }, 'text': { 'data': 'Click Here', 'size': 36, 'style': 'bold', 'name': 'text1', 'hOffset': 250, 'vOffset': 100, 'alignment': 'center', } }}
What if you want to remove all Json Properties that has a value of Integer Type. What would be a good way to achieve it if the format of Json is unknown ?
I ended up writing an extension method.
public static class Extensions { public static JToken RemoveFieldTypes(this JToken token,params JTokenType []fieldTypes) { JContainer container = token as JContainer; if (container == null) return token; var tokensToRemove = new List<JToken>(); foreach (JToken el in container.Children()) { JProperty p = el as JProperty; if(p!=null && fieldTypes.Contains(p.Value.Type)) { tokensToRemove.Add(el); } el.RemoveFieldTypes(fieldTypes); } foreach (JToken el in tokensToRemove) { el.Remove(); } return token; } }
Client Code Sample
JToken nodeList = JToken.Parse(strJson); nodeList.RemoveFieldTypes(JTokenType.Integer);
Sample Ouput
{ "widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window" }, "image": { "src": "Images/Sun.png", "name": "sun1", "alignment": "center" }, "text": { "data": "Click Here", "style": "bold", "name": "text1", "alignment": "center" } } }