Introduction
This post explains how to remove a JSON key in JSON result in MVC or C#
We can create our own converter class:
- public class JsonKeysConverter : JsonConverter
- {
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- Module o = (Module)value;
- JObject newObject = new JObject(new JProperty(o.Name, o.Permission));
- newObject.WriteTo(writer);
- }
-
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
- {
- throw new NotImplementedException("The type will skip the converter.");
- }
-
- public override bool CanRead
- {
- get { return false; }
- }
-
- public override bool CanConvert(Type objectType)
- {
- return true;
- }
- }
-
- [JsonConverter(typeof(JsonKeysConverter))]
- public class Module
- {
- public string Name { get; set; }
- public string[] Permission { get; set; }
- }
-
- public class Role
- {
- public class Roles
- {
- public Dictionary<string, List<string>> Modules {get; set;}
- }
- }
-
- public static string json()
- {
- var oRoles = new Roles();
- oRoles.modules = new Module[] {
- new Module(){
- Name="Page-Profile",
- Permission=new string[]{ "Edit","View","Delete"}
- },
- new Module(){
- Name="User",
- Permission=new string[]{ "Edit","View","Delete","Update"}
- }
- };
- var json = Newtonsoft.Json.JsonConvert.SerializeObject(oRoles);
-
-
- Dictionary<string, List<string>> modules = new Dictionary<string, List<string>>();
- modules.Add("Page-Profile", new List<string>() { "Edit", "View", "Delete"});
- modules.Add("User", new List<string>() { "Edit", "View", "Delete", "Update"});
-
- return JsonConvert.SerializeObject(modules);
Output
{"Page-Profile":["Edit","View","Delete"],"User":["Edit","View","Delete","Update"]}