首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用ASP.NET将关联数组转换为JSON并将其作为POST请求的一部分发送?

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

Stack Overflow用户
提问于 2013-03-22 03:40:29
回答 1查看 483关注 0票数 2

我正在为用PHP开发的REST API编写一些示例代码片段,虽然我可以设法获得一个"Ruby“示例,但我还没有找到一个像样的ASP.NET (图形)示例。我想知道是否有ASPer可以帮助翻译下面的PHP,它发出一个以JSON字符串作为有效负载的POST请求。

需要注意的主要事情是,POST需要一个命名参数"data“,它是一个JSON字符串。

代码语言:javascript
复制
    $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 )
      }
    }

谢谢你的帮助--我讨厌发布这样的东西,但也许它将来也会对其他人有帮助!

R

作为对评论的回应-我真正的帮助请求来自于缺乏一个ASP环境来调试/测试一个例子。例如- @Chris发布了一个链接,虽然从表面上翻译它看起来微不足道(尝试如下),但我的问题是我不仅仅是以普通的POST方式发送数据:

代码语言:javascript
复制
param=val&param2=val2 

它需要像这样:

代码语言:javascript
复制
data={JSONString}

其中JSONString是由关联数组生成的。那么问题就出现在ASP中的关联数组(或者更确切地说没有关联数组?-- http://blog.cloudspotting.co.uk/2010/03/26/associative-arrays-in-asp-net/),然后如何将不存在的关联数组编码成JSON字符串,或者如果我尝试使用NamedValueCollection呢?ASP中对JSON的支持似乎也参差不齐,所以我肯定会需要一个特殊的接口?

代码语言:javascript
复制
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);

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

代码语言:javascript
复制
string jsondata="";



StringBuilder data = new StringBuilder();

在使用UrlEncoding时,下面这行代码会中断吗?

代码语言:javascript
复制
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());
}

所以我想我的问题应该给出上面被黑客攻击的例子--有人能告诉我这是不是正确的,或者提供其他帮助?

EN

回答 1

Stack Overflow用户

发布于 2013-03-22 04:51:41

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

代码语言:javascript
复制
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);

结合this tool,我发现它是目前最好的.Net/JSon组合。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15556570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档