如何将关联数组转换为JSON并使用ASP.NET将其作为POST请求的一部分发送?

时间:2022-12-01 16:26:29

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.

我正在为用PHP开发的REST API编写一些示例代码片段,虽然我可以获得一个“Ruby”示例,但我还没有找到一个像样的ASP。NET(图)示例,这是等价的。我想知道是否有ASPer可以提供以下PHP的细节翻译,它以JSON字符串作为其有效负载发出POST请求。

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

需要注意的是,POST需要一个名为“data”的参数,即JSON字符串。

    $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

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:

作为对表扬的回应——我真正的请求是因为缺少一个用于调试/测试示例的ASP环境。例如,@Chris发布了一个链接,虽然从表面上看它的翻译很琐碎(尝试如下),但我的问题是,我并不是以普通的POST方式发送数据:

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?

JSONString是由关联数组组成的。然后,ASP中的关联数组出现了问题(或者明显缺乏关联数组?——http://blog.cloudspotting.co.uk/2010/03/26/ associatedarray -in-asp-net/),然后如何将一个不存在的关联数组编码成JSON字符串,或者如果我尝试使用NamedValueCollection ?在ASP中,JSON支持似乎是不稳定的,所以我确定需要一个特殊的接口?

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?

由于ASP实际上没有关联数组,我如何将数据转换成JSON ?

string jsondata="";



StringBuilder data = new StringBuilder();

Does the line below break things when using UrlEncoding?

当使用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?

所以我想我的问题应该给出上面被黑客攻击的例子——有人能告诉我这是对的还是有帮助的?

1 个解决方案

#1


1  

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

你有试过jSon.Net ?http://james.newtonking.com/pages/json-net.aspx的例子:

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.

结合这个工具,我发现它是最好的。net / json组合。

#1


1  

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

你有试过jSon.Net ?http://james.newtonking.com/pages/json-net.aspx的例子:

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.

结合这个工具,我发现它是最好的。net / json组合。