Home > Mobile >  Serialize dynamic response to key value pair C#
Serialize dynamic response to key value pair C#

Time:02-02

I am trying to retrieve a response from an internal API and one of the objects in the response has dynamic fields. Something like this.

{
   "className": "grade12",
   "School": "peg school",
   "attributes": {
      "propA": ["a1","a2","a3"],
      "propB": ["b1","b2","b3",
      "propC": ["c1","c2","c3"],
      .
      .
      .
      "propZ": ["1","2","3"]
   },
   "Create": "2022-01-31"
}

In the attributes field, there can be any number of fields . It can be empty or have 30 values. I would like to serialize something like

public class Fields
    {
        public string Name { get; set; }
        public List<string> Value { get; set; }
     
    }

    public class Parent
    {
        public string className { get; set; }
        public string School { get; set; }
        public List<Fields> AllFields { get; set; }
        public string Create { get; set; }
    }

So that when I serialize I will have

{
   "class": "grade12",
   "School": "peg school",
   "AllFields": [
      {
         "Name": "propA",
         "value": ["a1","a2","a3"]
      },
      {
         "Name": "propA",
         "value": ["a1","a2","a3"]
      }
   ],
   "Create": "2022-01-31"
}

So how can I achieve this?

CodePudding user response:

You can easily achieve this by creating a DTO object based on your Parent class where you can convert the dictionary into a list of custom objects. Something like this:

public class Base
{
    public string className { get; set; }
    public string School { get; set; }
    public string Create { get; set; }
}

public class Field
{
    public string Name { get; set; }
    public List<string> Value { get; set; }

    public Field(KeyValuePair<string, List<string>> pair)
    {
        Name = pair.Key;
        Value = pair.Value;
    }
}

public class Parent : Base
{
    public Dictionary<string, List<string>> attributes { get; set; }
}

public class ParentDTO : Base
{
    public List<Field> AllFields { get; set; }

    public ParentDTO(Parent parent)
    {
        className = parent.className;
        School = parent.School;
        Create = parent.Create;
        AllFields = parent.attributes.Select(i => new Field(i)).ToList<Field>(); 
    }
}

Then you can serialize ParentDTO object and you should obtain your desired output.

  •  Tags:  
  • Related