jishan siddique
jishan siddique

Reputation: 1895

Prepare custom json format return in MVC c#

I have two classes, namely Roles and Module in Module class I have two properties Name,Permission.

for now, just testing purpose I'm creating one demo code.

Class file

    public class Roles
    {
        public Module[] modules { get; set; }
        public Roles()
        {
            modules = new Module[] { };
        }
    }

    public class Module
    {
        public string Name { get; set; }
        public string[] Permission { get; set; }
    }

Controller code

public ActionResult Index()
{   
    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);
    return View(json);
}

It's working fine I'm getting result also but I want result like this.

Expected result.

{
  "modules": [
    {
      "Page-Profile": [
        "Edit",
        "View",        
        "Delete"
      ]
    },
    {
      "User": [
        "Edit",
        "View",
        "Update",
        "Delete"
      ]
    }
  ]
}

Currently I'm getting a result like this. is there any way to modify JSON remove all key and get only values.

{
  "modules": [
    {
      "Name": "Page-Profile",
      "Permission": [
        "Edit",
        "View",
        "Delete"
      ]
    },
    {
      "Name": "User",
      "Permission": [
        "Edit",
        "View",
        "Delete",
        "Update"
      ]
    }
  ]
}

Note: How to remove key properties i want only name value and in name value again i wan't all permission as mention in excpected result.

Upvotes: 0

Views: 1058

Answers (3)

Azz Falconer
Azz Falconer

Reputation: 44

Its working for me ,try this :

Code

public class Roles
{
    public Roles()
    {   
        modules = new List<Dictionary<string, List<string>>>();
    }

    public List<Dictionary<string, List<string>>> modules { get; set; }
}



/*Index*/
public ActionResult Index()
{
    var oRoles = new Roles();   
    var userRolePermissionsAndModulesList =  userRolePermissionManager.GetAllUserRolePermissionsAndModules(userId);

    foreach (var module in userRolePermissionsAndModulesList)
    { 
        var objPermissionWithModules = new Dictionary<string, List<string>>();
        var permission = new List<string> { };

        if (module.CanCreate)
        permission.Add("Create");
        if (module.CanDelete)
        permission.Add("Delete");
        if (module.CanEdit)
        permission.Add("Update");
        if (module.CanView)
        permission.Add("View");

        objPermissionWithModules.Add(module.ModuleName, permission);
        oRoles.modules.Add(objPermissionWithModules);
    } 

    var json = Newtonsoft.Json.JsonConvert.SerializeObject(oRoles);

    return View(json);
}

Please compare your output :

{
   "modules":[
      {
         "Page-Profile":[
            "Edit",
            "View",
            "Delete"
         ]
      },
      {
         "user":[
            "Edit",
            "View",
            "Delete",
            "Update"
         ]
      }
   ]
}

Upvotes: 0

user1672994
user1672994

Reputation: 10849

There are two way to achieve it

  1. By writing the custom converter
  2. By changing the Roles object

By writing the custom converter

You can implement the CustomJsonConverter as follows which convert the name to key and permission to value:

public class FlatternKeysConverter : 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("Unnecessary because CanRead is false. The type will skip the converter.");
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

And attach the JsonConverter as

[JsonConverter(typeof(FlatternKeysConverter))]
public class Module
{
    public string Name { get; set; }
    public string[] Permission { get; set; }
}

The generated JSON will be as follows :

{"modules":[{"Page-Profile":["Edit","View","Delete"]},{"User":["Edit","View","Delete","Update"]}]}

By changing the Roles object

Change the roles object to dictionary

public class Role
{
    public class Roles
    {
        public Dictionary<string, List<string>> Modules {get; set;}
    }
}

You can check the https://dotnetfiddle.net/Hs3i04 dotnet fiddle which shows both approaches.

Upvotes: 1

sam
sam

Reputation: 1985

Remove Module class and try changing Roles as follows to get expected json format:

    public class Roles
    {
        public Roles()
        {
            modules = new Dictionary<string, List<string>>();
        }
        public Dictionary<string, List<string>> modules { get; set; }
    }

Controller Action code:

public ActionResult Index()
{   
    var oRoles = new Roles();
    oRoles.modules.Add("Page-Profile", new List<string>{"Edit","View","Delete"});
    oRoles.modules.Add("user", new List<string>{"Edit","View","Delete","Update"});
    // Not sure why you are serializing to json. 
    // you can directly return View(oRoles) or PartialView(oRoles)
    var json = Newtonsoft.Json.JsonConvert.SerializeObject(oRoles);
    return View(json);
}

Upvotes: 1

Related Questions