0

For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.

  • 1
    You need to show the code which converts your `Dictionary` to `JSON` and also, will be good to see how you read multiple records – Vikhram Jun 07 '17 at 10:08
  • For a start there is no need to mark your dictionary as `` as you are casting the values o string anyway. Secondly as @Vikhram said - it depends on the JSON serializer you are using. Newtonsoft for instance, provides a class specifically for this called `JObject`. – Michael Coxon Jun 07 '17 at 10:18
  • can you check this https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c convert dictionary into json.. – muiz Jun 07 '17 at 10:31
  • https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c can you please check – muiz Jun 07 '17 at 10:33
  • i think the use of dictionary is a bad idea. If the response may have data with the same column name, then there will be an issue thrown because of the duplicate. I suggest you to use List – kbvishnu Jun 07 '17 at 10:55

3 Answers3

0

Maybe this library could help you, it could save you time

http://www.newtonsoft.com/json

Guille89
  • 81
  • 8
0

You should create a C# class similar to your JSON structure.

public class SomeClassName
{
    public string name { get; set; }
    public string date { get; set; }
}

then instead of Dictionary, use List of the above class as follow:

List<SomeClassName> t = new List<SomeClassName>();
for (int i = 0; i < reader.FieldCount; i++)
{
    t.Add(new SomeClassName() { name = reader.GetName(i), date = reader.GetValue(i).ToString() });
}
_response.data.Add(t);
Kiran Beladiya
  • 441
  • 1
  • 5
  • 11
0

You can use an anonymous type in C#.

new { key = value, ...};

e.g.

List<object> lst = new List<object>();
lst.Add(new { Name = "Andrey", Age = 31 });
lst.Add(new { Name = "Martha" });

// print [{"Name":"Andrey","Age":31},{"Name":"Martha"}]
Console.WriteLine(JsonConvert.SerializeObject(lst));
zapic
  • 1
  • 1
  • Both the key and value is generated dynamically and we are not sure of what it could be. So we cannot directly add name and age to the list! – Shriram Manoharan Jun 07 '17 at 10:57