0

I want to deserialize a json object in c# using JsonSerializer.Deserialize of System.Text.Json. The json looks like this:

{
   "id":10,
   "authorization_ids":[
      
   ],
   "karma_user_ids":[
      2
   ],
   "group_ids":{
      "2":[
         "full"
      ],
      "4":[
         "read"
      ],
      "5":[
         "overview"
      ],
      "7":[
         "change",
         "overview"
      ],
      "10":[
         "create"
      ]
   }
}

But the property group_ids contains objects with dynamic property names that actually correspond to the ID of a group.

{
  2  : {full}
  4  : {read}
  5  : {overview}
  7  : {change, overview}
  10 : {create}
}

Now I want to deserialize group_ids to an object like this:

public class GroupPermission
{
    public int GroupID { get; set; }
    public Permission Permission { get; set; }

    public GroupPermission() { }
}

[Flags]
public enum Permission
{
    full = 1,
    read = 2,
    overview = 4,
    change = 8,
    create = 16
}

Is this possible? Can someone point me the right direction?

dbc
  • 104,963
  • 20
  • 228
  • 340
B4DschK4Pp
  • 165
  • 1
  • 10
  • 1
    Can you please add full JSON with `group_ids` JSON data? Not clear its behavior – Sachith Wickramaarachchi Oct 24 '21 at 18:13
  • @SachithWickramaarachchi Tanks, but what do you mean? The json of group_ids is the second json code block above. But I added a comment to make it more clear. – B4DschK4Pp Oct 24 '21 at 18:25
  • Neither block 1 nor block 2 is valid JSON. Please show your *actual* JSON – Charlieface Oct 24 '21 at 20:42
  • @Charlieface right... Sorry. Updated the thread and added the json. – B4DschK4Pp Oct 24 '21 at 21:00
  • Does this answer your question? [json deserialization to C# with dynamic keys](https://stackoverflow.com/questions/65727513/json-deserialization-to-c-sharp-with-dynamic-keys) In this case, `group_ids` should be deserialized to `Dictionary>` and the dictionary keys are the IDs – Charlieface Oct 24 '21 at 21:28
  • @B4DschK4Pp Do I understand correctly that you want to deserialize the `group_ids` to a collection of `GroupPermission`? – Peter Csala Oct 25 '21 at 07:42

1 Answers1

1

Should be something like this:

    public class RootObject
    {
        [JsonPropertyName("id")]
        public int Id {get;set;}

        [JsonPropertyName("authorization_ids")]
        public List<int> AuthorizationIds {get;set;}
        
        [JsonPropertyName("karma_user_ids")]
        public List<int> KarmaUserIds {get;set;}

        [JsonPropertyName("group_ids")]
        public Dictionary<int, List<string>> GroupIds {get;set;}

        public RootObject()
        {
            AuthorizationIds = new List<int>();
            KarmaUserIds = new List<int>();
            GroupIds = new Dictionary<int, List<string>>();
        }
    }

To test it:

public static void Main(string[] args)
{
    var json = File.ReadAllText("./file.json");
    var objs = JsonSerializer.Deserialize<RootObject>(json);
}