Introduction
This post explains how to remove a JSON key in JSON result in MVC or C#
We can create our own converter class:
  1. public class JsonKeysConverter : JsonConverter
  2. {
  3. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  4. {
  5. Module o = (Module)value;
  6. JObject newObject = new JObject(new JProperty(o.Name, o.Permission));
  7. newObject.WriteTo(writer);
  8. }
  9. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  10. {
  11. throw new NotImplementedException("The type will skip the converter.");
  12. }
  13. public override bool CanRead
  14. {
  15. get { return false; }
  16. }
  17. public override bool CanConvert(Type objectType)
  18. {
  19. return true;
  20. }
  21. }
  22. [JsonConverter(typeof(JsonKeysConverter))]
  23. public class Module
  24. {
  25. public string Name { get; set; }
  26. public string[] Permission { get; set; }
  27. }
  28. public class Role
  29. {
  30. public class Roles
  31. {
  32. public Dictionary<string, List<string>> Modules {get; set;}
  33. }
  34. }
  35. public static string json()
  36. {
  37. var oRoles = new Roles();
  38. oRoles.modules = new Module[] {
  39. new Module(){
  40. Name="Page-Profile",
  41. Permission=new string[]{ "Edit","View","Delete"}
  42. },
  43. new Module(){
  44. Name="User",
  45. Permission=new string[]{ "Edit","View","Delete","Update"}
  46. }
  47. };
  48. var json = Newtonsoft.Json.JsonConvert.SerializeObject(oRoles);
  49. Dictionary<string, List<string>> modules = new Dictionary<string, List<string>>();
  50. modules.Add("Page-Profile", new List<string>() { "Edit", "View", "Delete"});
  51. modules.Add("User", new List<string>() { "Edit", "View", "Delete", "Update"});
  52. return JsonConvert.SerializeObject(modules);
Output
  • {"Page-Profile":["Edit","View","Delete"],"User":["Edit","View","Delete","Update"]}