Home > Back-end >  Customize object serialization to Json in c#
Customize object serialization to Json in c#

Time:08-20

I am making an asp.net core web api and i want to return Ok(JsonList) in a specific format I have a list of the following object:

public class obj 
{ 
  string schoolName;
  int studentscount;
  int teacherscount;
}

that would be serialized by default to:

[{"schoolName":"name_1",
  "studentscount" : "5",
  "teacherscount" : "2"
 },
{"schoolName":"name_2",
  "studentscount" : "10",
  "teacherscount" : "3"
 }]

I want the name property to be the name of the object :

    [{
   "name_1":{
      "studentscount" : "5",
      "teacherscount" : "2"
     },
    "name_2:"{
      "studentscount" : "10",
      "teacherscount" : "3"
     }
   }]

CodePudding user response:

you can create a new class and try this


    Dictionary<string, Counts> counts = JArray.Parse(json).ToDictionary(j => (string)j["schoolName"], j => new Counts
    {
        studentscount = (int)j["studentscount"],
        teacherscount = (int)j["teacherscount"]
    });

    json = JsonConvert.SerializeObject(counts, Newtonsoft.Json.Formatting.Indented);

public class Counts
{
    public int studentscount { get; set; }
    public int teacherscount { get; set; }
}

result

{
  "name_1": {
    "studentscount": 5,
    "teacherscount": 2
  },
  "name_2": {
    "studentscount": 10,
    "teacherscount": 3
  }
}

but if for some reasons you still need an array

var countsArray = new List<Dictionary<string,Counts>> {counts};

json=JsonConvert.SerializeObject(countsArray,Newtonsoft.Json.Formatting.Indented);

result

[
  {
    "name_1": {
      "studentscount": 5,
      "teacherscount": 2
    },
    "name_2": {
      "studentscount": 10,
      "teacherscount": 3
    }
  }
]
  • Related