Currently, I am using the below code to make JSON data from list of objects.
public IActionResult getWardsFromVDC(long vdc_id)
{
try
{
List<Ward> wards = wardRepo.getByVdcId(vdc_id).ToList();
List<Dictionary<string, string>> values = new List<Dictionary<string, string>>();
foreach (var ward in wards)
{
Dictionary<string, string> value = new Dictionary<string, string>();
value["ward_id"] = ward.ward_id.ToString();
value["ward_name"] = ward.ward_name;
values.Add(value);
}
Dictionary<string, object> data = new Dictionary<string, object>();
data["data"] = values;
var json = JsonConvert.SerializeObject(data);
return Json(json);
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
List<Ward> wards = wardRepo.getByVdcId(vdc_id).ToList();
is getting list of Ward class from database. Then a loop is used to put all the values in List of Dictionaries .
Dictionary<string, object> data = new Dictionary<string, object>(); data["data"] = values; var json = JsonConvert.SerializeObject(data);
is putting all those values in "data" key in another dictionary and then value is serialized and returned as JSON
The JSON data formed is :
{
"data": [
{
"ward_id": "132",
"ward_name": "1"
},
{
"ward_id": "133",
"ward_name": "2"
},
{
"ward_id": "134",
"ward_name": "3"
},
{
"ward_id": "135",
"ward_name": "4"
},
{
"ward_id": "136",
"ward_name": "5"
},
{
"ward_id": "137",
"ward_name": "6"
},
{
"ward_id": "138",
"ward_name": "7"
},
{
"ward_id": "139",
"ward_name": "8"
},
{
"ward_id": "140",
"ward_name": "9"
},
{
"ward_id": "141",
"ward_name": "10"
},
{
"ward_id": "142",
"ward_name": "11"
},
{
"ward_id": "143",
"ward_name": "12"
}
]
}
To build even a simple data , I am creating dictionary and list of dictionaries and again adding data key .
Is there any simple way to build JSON in same format but in simplest way?
ward_id
into a string? This is very suspicious. \$\endgroup\$ward_id
being converted to string? The definition forWard
is missing. The description of what the consumer of the service expects is missing. \$\endgroup\$