【问题标题】:How can I convert an associative array to JSON and send it as part of a POST request using ASP.NET?如何使用 ASP.NET 将关联数组转换为 JSON 并将其作为 POST 请求的一部分发送?
【发布时间】:2013-03-21 19:40:29
【问题描述】:

我正在为用 PHP 开发的 REST API 编写一些示例代码片段,虽然我可以设法获得一个“Ruby”示例,但我还没有找到一个像样的 ASP.NET(数字)示例将是等效的。我想知道是否有任何 ASPer 可以帮助对以下 PHP 进行详细翻译,该 PHP 发出一个带有 JSON 字符串作为其有效负载的 POST 请求。

主要需要注意的是,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 )
      }
    }

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

R

为了回应评论 - 我真正的帮助请求是由于缺乏 ASP 环境来调试/测试示例。例如 - @Chris 发布了一个链接,虽然按面值翻译它似乎微不足道(尝试如下),但我的问题是我不只是以正常的 POST 方式发送数据:

param=val&param2=val2 

它需要像这样:

data={JSONString}

其中 JSONString 由关联数组组成。然后问题出现在 ASP 中的关联数组(或者明显缺乏关联数组?--http://blog.cloudspotting.co.uk/2010/03/26/associative-arrays-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);

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

string jsondata="";



StringBuilder data = new StringBuilder();

使用 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());
}

所以我想我的问题应该是上面被黑的例子 - 有人可以告诉我这是否正确或有其他帮助吗?

【问题讨论】:

  • forums.asp.net/post/3384091.aspx - Google 中的 5 秒。
  • @ChrisL 我认为 OP 在他发布此内容的方式上非常有礼貌(尽管缺乏努力)。没有必要粗鲁。
  • 嗨罗斯!代码翻译请求在 Stack Overflow 的范围内并不适用。如果您自己尝试过翻译,并且有一个关于您卡在哪里的具体问题,那将是一个合适的问题。现在,这太宽泛了,可能对未来的访问者没有帮助,并且表现出缺乏努力(请注意,我并不是说你没有尝试过任何东西,我是只是说这就是它的样子)。
  • 谢谢@jadarnel27 - 我明白了 - 并不是我没有尝试过什么,而是由于缺乏 ASP 环境而无法真正“尝试”任何东西。正如 Chris 提供的那样,我遇到了许多示例,但是问题出现在 ASP 中的关联数组混乱周围,然后从那里走下坡路,此时我认为 ASP vet 可以快速解决一些问题来帮助我。我们将看看上述阐述是否非法不仅仅是反对投票。

标签: php asp.net json post


【解决方案1】:

你试过 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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2020-04-25
    相关资源
    最近更新 更多