Search code examples
c#jsonjavascriptserializer

Serializing c# class to JSON string with custom column name


I have this result

{
    "StatusCode": "200",
    "Description": "Success",
    "Data": [
        {
            "Language_Key": "btn_select_country",
            "En_Val": "SELECT COUNTRY",
            "Ar_Val": "اختر الدولة"
        },
        {
            "Language_Key": "btn_continue",
            "En_Val": "CONTINUE",
            "Ar_Val": "استمرار"
        }
      ]
}

I would like to achieve below result.

{
"StatusCode":"200",
"Description":"Success",
"Data":{
    "btn_select_country":{
          "En_Val":"SELECT COUNTRY",
          "Ar_Val":"اختر الدولة"
    },
    "btn_continue":{
          "En_Val":"CONTINUE",
          "Ar_Val":"استمرار"
    }
  }
}

I want Language_Key to replace with column name and with 2 child nodes as EN and AR below is my code

enter image description here

Any hint is appreciated. Thanks


Solution

  • you serialize a dictionary where the key is your Language_Key:

    Dictionary<string, Translation> dict = countryObj
        .ToDictionary(o => o.Language_Key, o => new Translation { Ar_Val = o.Ar_Val, En_Val = o.En_Val});
        
    rs.Data =  dict;
    json = new JavScriptSerializer().Serialize(rs);