Ross
Ross

Reputation: 1679

How can I convert an associative array to JSON and send it as part of a POST request using ASP.NET?

I'm writing some sample code fragments for a REST API that's developed in PHP and while I can manage to get a "Ruby" example, I haven't been able to find a decent ASP.NET (figures) example that would be equivalent. I was wondering if any ASPer could help out with a nitty-gritty translation of the following PHP which issues a POST request with a JSON string as its payload.

The main thing to note is that the POST requires one named parameter "data" which is a JSON string.

    $key='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';    // This would be your customer key
    $map='USA';
    $accountid='000';                                   // this would be your account id
    // add some zips to an array
    $zips[]=22201;
    $zips[]=90210;
    $zips[]=10001;

    // We encode an array into JSON
    $data = array("map" => $map, "zips"=>$zips, "accountid" => $accountid, "custkey" => $key);                                                                    
    $data_string = json_encode($data);                       
    // IMPORTANT - the API takes only one POST parameter - data 
    $postdata="data=$data_string";

    // we use curl here, but Zend has Rest interfaces as well...
    $ch = curl_init('https://www.example.com//test/');                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_POST, 1);         // make sure we submit a POST!

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
      $result=curl_error($ch);
    } else {
      curl_close($ch);
    }

    $jsonObj=json_decode($result);
    if($jsonObj->success){
      $coordinates=$jsonObj->coordinates;               
      foreach($coordinates->coordinates as $coord){
        //... application logic here ( construct XML for the map )
      }
    }

Thanks for the help - I hate posting stuff like this, but maybe it'll help someone else in the future as well!

R

In response to commments - my real request for help arises out of the lack of an ASP environment to debug/test an example. For example - @Chris posted a link, and while translating it at face value seems trivial (attempt below), my problem is I'm not just sending data in the normal POST fashion:

param=val&param2=val2 

It needs to go like:

data={JSONString}

where the JSONString is made from an associative array. Then the problem arises with associative arrays in ASP (or rather apparent lack thereof? -- http://blog.cloudspotting.co.uk/2010/03/26/associative-arrays-in-asp-net/) in general and then how to encode a non-existent associative array into a JSON string or if I try to use NamedValueCollection instead? It also appears that JSON support in ASP is spotty, so I'm sure there is going to be a need for a special interface?

using System.Web;

Uri address = new Uri("http://www.example.com/test/");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string map = "USA";
string accountid = "000";
string data =""; 
NameValueCollection data = new NameValueCollection();
data.Add("custkey", key);
data.Add("map", map);
data.Add("accountid", accountid);

How can I convert data to JSON since ASP doesn't actually have associative arrays?

string jsondata="";



StringBuilder data = new StringBuilder();

Does the line below break things when using UrlEncoding?

data.Append("data=" + HttpUtility.UrlEncode(jsondata));

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

// Set the content length in the request headers
request.ContentLength = byteData.Length;

// Write data
using (Stream postStream = request.GetRequestStream())
{
  postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
   // Get the response stream
   StreamReader reader = new StreamReader(response.GetResponseStream());
   // Console application output
   string jsonResponse =reader.ReadToEnd());
}

So I guess my question should be given the above hacked example - can someone tell me if this is correct or assist otherwise?

Upvotes: 2

Views: 593

Answers (1)

Hanlet Escaño
Hanlet Escaño

Reputation: 17380

Have you tried jSon.Net? http://james.newtonking.com/pages/json-net.aspx Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Combined with this tool I find it is the best .Net/JSon combination out there.

Upvotes: 1

Related Questions