Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve desired JSON format using C#.NET HashTable

Tags:

c#

hashtable

How to achieve below mentioned JSON format using C#.NET HashTable

{"DoWorkResult":
      [
       {"Perimeter":"55},
       {"Mortgage":"540"},
       {"Area":"1000"}
      ]
}

I tried to do this with Hashtable with an example as like below

    Hashtable hashtable = new Hashtable();

    hashtable.Add("Area", 1000);
    hashtable.Add("Perimeter", 55);
    hashtable.Add("Mortgage", 540);

But the result is as shown below

{"DoWorkResult":
      [
       {"Key":"Perimeter","Value":55},
       {"Key":"Mortgage","Value":540},
       {"Key":"Area","Value":1000}
      ]
}

Note : I am returning the actual Hash table in a WCF service method, and i am using an ajax call to read the output from backend.

Ajax Method i am using in front end :

$.ajax({
            type: 'POST',
            url: '/Service.svc/DoWork',
            success: function(data) {
                alert(data);
            }
        });
like image 249
balanv Avatar asked Feb 19 '23 08:02

balanv


1 Answers

Using both JavaScriptSerializer and Json.Net

var list = new ArrayList();
list.Add(new { Area = 1000 });
list.Add(new { Perimeter = 55 });
list.Add(new { Mortgage = 540 });

var s1 = new JavaScriptSerializer().Serialize(new { DoWorkResult = list });
var s2 = JsonConvert.SerializeObject(new { DoWorkResult = list });
like image 164
L.B Avatar answered Feb 22 '23 21:02

L.B