1
\$\begingroup\$

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?

\$\endgroup\$
  • 7
    \$\begingroup\$ To whoever is voting to close this question: please provide which context should be added for the question to be on-topic. I see a problem statement, working code and example output. OP is looking for a simplification of the code provided, which is a perfectly good start for a review. \$\endgroup\$ – Mast Sep 14 '18 at 7:46
  • \$\begingroup\$ Why are you converting the ward_id into a string? This is very suspicious. \$\endgroup\$ – t3chb0t Sep 14 '18 at 13:44
  • \$\begingroup\$ @t3chb0t i used dictionary of string . That is the reason why I did so sir \$\endgroup\$ – Dot Net developer Sep 14 '18 at 13:45
  • \$\begingroup\$ @Mast here they are: Why is ward_id being converted to string? The definition for Ward is missing. The description of what the consumer of the service expects is missing. \$\endgroup\$ – t3chb0t Sep 14 '18 at 14:02
3
\$\begingroup\$

Anonymous types are going to be your friend here. You don't need to have list or dictionary at all.

First you don't need to call ToList() from your repository.

Now we can just project out the properties you want like so

wards.Select(w => new
{
     ward_id = w.ward_id.ToString(),
     w.ward_name
})

JsonConvert will serialize an IEnumerable as an array. this will get your square bracket around the "Wards" and have the two properties you would like and having the Id converted to a string.

Now you just need the "data" object to contain the IEnumerable. Again making an anonymous type.

var data = new
{
    data = wards.Select(w => new
    {
        ward_id = w.ward_id.ToString(),
        w.ward_name
    })
};

var json = JsonConvert.SerializeObject(data);

That's it. That should get you what you want.

\$\endgroup\$
  • \$\begingroup\$ Thank you sir. I will try it out. I knew my idea was not good. So I posted it here for review. Instead of answering I got downvoted. I would have appreciated an answer with downvote. But noone seemed interested. \$\endgroup\$ – Dot Net developer Sep 14 '18 at 3:46
  • \$\begingroup\$ This is completely unnecessary because json.net would map the Ward object without the Select projection to the exact same result. \$\endgroup\$ – t3chb0t Sep 14 '18 at 13:56
  • 1
    \$\begingroup\$ You don't know if he has extra properties on the Ward object he doesn't want and plus he wanted the ToString on the id. without ToString he wouldn't get the quotes around the number like he wanted with the output \$\endgroup\$ – CharlesNRice Sep 14 '18 at 14:04
  • \$\begingroup\$ @CharlesNRice Exactly sir. I have shown the output format too. \$\endgroup\$ – Dot Net developer Sep 14 '18 at 14:09
  • \$\begingroup\$ @DotNetdeveloper yes, you've shown the output format but when I asked you why you convert ward_id to string you told me because the dictionary uses such - this reasoning is senseless thus the output format is 99.99% wrong and the conversion is also not optimal but since you're not willing to share more information I cannot give you any more advice. \$\endgroup\$ – t3chb0t Sep 14 '18 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.