菜鸟教程小白 发表于 2022-12-13 02:03:25

php - 将方法 nsdictionary 发布到 json 对象 iOS objective-c


                                            <p><p>我正在尝试将字典数组发送到服务器,在此之前我正在转换为 json 格式</p>

<p>注意:- 服务器运行良好,我在 android 中的 friend 正在获取成功发布方法的响应和数据</p>

<p>下面是我的post方法代码:-</p>

<pre><code>NSError *error;
NSMutableDictionary *tvarns = [ init];
tvarns[@&#34;order_cart&#34;]=_order_cart;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tvarns
                                                   options:NSJSONWritingPrettyPrinted error:&amp;error];
NSLog(@&#34;%@&#34;,jsonData);
NSString* order_cart;

order_cart = [ initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@&#34;%@&#34;,order_cart);

NSString *post = ;
NSData *postData = ;
//Next up, we read the postData&#39;s length, so we can pass it along in the request.
NSString *postLength = ];
// Now that we have what we&#39;d like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [ init];
];
;
;
;
NSLog(@&#34;the data Details is %@&#34;, post);
//   And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = ];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *requestReply = [ initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    NSLog(@&#34;Reply = %@&#34;, requestReply);
    //   NSError *error;
    NSDictionary *jsonDict = ; // you need to convert to dictionary object
    NSLog(@&#34;requestReply: %@&#34;, jsonDict);

}] resume];

;
}
</code></pre>

<p>服务器想要的值是</p>

<pre><code>{&#34;order_cart&#34;:[{&#34;customer_id&#34;:&#34;114&#34;,&#34;item_id&#34;:14,&#34;_id&#34;:&#34;591d3822f55e2270202d8ff1&#34;,&#34;item_name&#34;:&#34;Bira White&#34;,&#34;item_quantity&#34;:&#34;2&#34;,&#34;price&#34;:&#34;180.0&#34;,&#34;qr_code&#34;:&#34;table21&#34;,&#34;phone&#34;:&#34;7008841769&#34;,&#34;customer_name&#34;:&#34;Samanthaa&#34;},{&#34;customer_id&#34;:&#34;114&#34;,&#34;item_id&#34;:15,&#34;_id&#34;:&#34;591d3822f55e2270202d8ff0&#34;,&#34;item_name&#34;:&#34;Bira Blonde&#34;,&#34;item_quantity&#34;:&#34;2&#34;,&#34;price&#34;:&#34;200.0&#34;,&#34;qr_code&#34;:&#34;table21&#34;,&#34;phone&#34;:&#34;7008841769&#34;,&#34;customer_name&#34;:&#34;Samanthaa&#34;}]}
</code></pre>

<p>我的 nslog 是</p>

<pre><code>2017-06-28 16:16:41.334 Barebones the data Details is {
&#34;order_cart&#34; : [
{
&#34;phone&#34; : &#34;9047038606&#34;,
&#34;item_quantity&#34; : &#34;7&#34;,
&#34;qr_code&#34; : &#34;table21&#34;,
&#34;item_name&#34; : &#34;Bottled Water&#34;,
&#34;price&#34; : &#34;175&#34;,
&#34;customer_id&#34; : &#34;116&#34;,
&#34;customer_name&#34; : &#34;Akshay&#34;
},
{
&#34;phone&#34; : &#34;9047038606&#34;,
&#34;item_quantity&#34; : &#34;2&#34;,
&#34;qr_code&#34; : &#34;table21&#34;,
&#34;item_name&#34; : &#34;Fresh Lime Soda(Sweet, Salt, Plain)&#34;,
&#34;price&#34; : &#34;158&#34;,
&#34;customer_id&#34; : &#34;116&#34;,
&#34;customer_name&#34; : &#34;Akshay&#34;
},
{
&#34;phone&#34; : &#34;9047038606&#34;,
&#34;item_quantity&#34; : &#34;2&#34;,
&#34;qr_code&#34; : &#34;table21&#34;,
&#34;item_name&#34; : &#34;Bottled Water&#34;,
&#34;price&#34; : &#34;50&#34;,
&#34;customer_id&#34; : &#34;116&#34;,
&#34;customer_name&#34; : &#34;Akshay&#34;
},
{
&#34;phone&#34; : &#34;9047038606&#34;,
&#34;item_quantity&#34; : &#34;2&#34;,
&#34;_id&#34; : &#34;591d3822f55e2270202d8ff0&#34;,
&#34;item_name&#34; : &#34;Bira Blonde&#34;,
&#34;price&#34; : &#34;86&#34;,
&#34;qr_code&#34; : &#34;table21&#34;,
&#34;customer_id&#34; : &#34;116&#34;,
&#34;item_id&#34; : &#34;3971&#34;,
&#34;customer_name&#34; : &#34;Akshay&#34;
},
{
&#34;phone&#34; : &#34;9047038606&#34;,
&#34;item_quantity&#34; : &#34;1&#34;,
&#34;qr_code&#34; : &#34;table21&#34;,
&#34;item_name&#34; : &#34;Bottled Water&#34;,
&#34;price&#34; : &#34;25&#34;,
&#34;customer_id&#34; : &#34;116&#34;,
&#34;customer_name&#34; : &#34;Akshay&#34;
   }
]
}
2017-06-28 16:16:41.485 Barebones Reply =   {&#34;order_id&#34;:3961,&#34;success&#34;:1}
&lt;script type=&#39;text/javascript&#39;    src=&#39;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js&#39;&gt;.      &lt;/script&gt;
&lt;script&gt;
var data_array=&#39;{&#34;source&#34;:{&#34;name&#34;:&#34;Kre8Tives&#34;,&#34;id&#34;:&#34;SJQ6kyA1&#34;,&#34;order_id&#34;:&#34;3961&#34;},&#34;customer&#34;:{&#34;firstname&#34;:&#34;&#34;,&#34;mobile&#34;:&#34;&#34;},&#34;tabType&#34;:&#34;table&#34;,&#34;tabId&#34;:&#34;591d3790498782970be66302&#34;,&#34;tableNumber&#34;:&#34;1&#34;,&#34;items&#34;:null}&#39;;
alert(data_array);
var settings = {
&#39;async&#39;: true,
&#39;crossDomain&#39;: true,
&#39;url&#39;: &#39;http://posistapi.com/api/v1/table_order/push?customer_key=8c982f5e9ef091e9d5c8fb142311b49a68049b102de5e0987ebce29755c454227fbc7573c7da4199f126524a3ac7a39a&amp;tabtype=table&#39;,
&#39;method&#39;: &#39;POST&#39;,
&#39;headers&#39;: {
&#39;postman-token&#39;: &#39;e200ae19-d083-a98a-6db3-53fc2f8bd73f&#39;,
&#39;cache-control&#39;: &#39;no-cache&#39;,
&#39;authorization&#39;: &#39;Basic &#39;,
&#39;content-type&#39;: &#39;application/json&#39;
},
&#39;processData&#39;: false,
&#39;data&#39;: data_array,
&#39;acceptUrl&#39;:&#39;http://test.kre8tives.com/barebon/order_confirm.php&#39;,
&#39;rejectUrl&#39;:&#39;http://test.kre8tives.com/barebon/order_confirm.php&#39;,
&#39;billPrintUrl&#39;:&#39;http://test.kre8tives.com/barebon/order_confirm.php&#39;

}

$.ajax(settings).done(function (response) {
console.log(response);
});
&lt;/script&gt;
2017-06-28 16:16:41.486 Barebones requestReply: (null)
</code></pre>

<p>我已转换为所需的儿子格式,但仍然没有收到服务器的回复</p>

<p>即使我发送返回我从服务器发送的数据,我也会得到空值!!为什么会这样???提前谢谢!!:)</p>

<p>这是我的 PHP 代码</p>

<pre><code>&lt;?php
include(&#39;order-function.php&#39;);
if($_SERVER[&#34;REQUEST_METHOD&#34;] == &#34;POST&#34;)
{

$order_cart=$_POST[&#39;order_cart&#39;];

$items=json_decode($order_cart,true);

include(&#39;dbconfig.php&#39;);
$response = array();
try
    {
      $total_item_price=0;

      foreach ($items[&#39;order_cart&#39;] as $item) {   //[&#39;order_cart&#39;]

      $customer_id=$item[&#39;customer_id&#39;];
      $customer_name=$item[&#39;customer_name&#39;];
      $phone=$item[&#39;phone&#39;];
    $_id=$item[&#39;_id&#39;];
      $item_name=$item[&#39;item_name&#39;];
      $item_quantity=$item[&#39;item_quantity&#39;];
      $price=$item[&#39;price&#39;];
      $qr_code=$item[&#39;qr_code&#39;];

$products[]=array(
      &#34;_id&#34;=&gt;&#34;$_id&#34;,
      &#34;item_name&#34;=&gt; $item_name,
      &#34;item_price&#34;=&gt; $price,
            &#34;item_quantity&#34;=&gt; $item_quantity

    );         

    $price_new+=$price;


       $item_push[]=array(
      &#34;id&#34;=&gt;&#34;$_id&#34;,
      &#34;rate&#34;=&gt; $price,
            &#34;quantity&#34;=&gt; $item_quantity

    );
      }


      $product_details=json_encode($products);
    $add_to_cart = &#34;INSERT INTO order_cart (customer_id,product_details,order_amount,qr_code) VALUES (&#39;$customer_id&#39;,&#39;$product_details&#39;,&#39;$price_new&#39;,&#39;$qr_code&#39;)&#34;;
      $result = mysqli_query($conn,$add_to_cart);
      $order_id=mysqli_insert_id($conn);

      if ($result) {

    $data[&#39;source&#39;]=array(&#34;name&#34;=&gt;&#34;Kre8Tives&#34;,
                            &#34;id&#34;=&gt;&#34;SJQ6kyA1&#34;,
                  &#34;order_id&#34;=&gt;&#34;$order_id&#34;
                );
    $data[&#39;customer&#39;]=array(
                        &#34;firstname&#34;=&gt;&#34;$customer_name&#34;,
                   &#34;mobile&#34;=&gt;&#34;$phone&#34;
                );
   $data[&#39;tabType&#39;]= &#34;table&#34;;
       $data[&#39;tabId&#39;]= &#34;591d3790498782970be66302&#34;;
       $data[&#39;tableNumber&#39;]= &#34;1&#34;;

       //items
       $data_one=json_encode($item_push,JSON_NUMERIC_CHECK);
       $data_new=json_decode($data_one);
       $data[&#39;items&#39;]=$data_new;

       $data_item=json_encode($data);


$response[&#34;order_id&#34;] = $order_id;
$response[&#34;success&#34;] = 1;

   // print_r(json_encode($data));die;


} else {
            $response[&#34;success&#34;] = 0;
      }







echo json_encode($response);
push_order($data_item);

    }
catch(Exception $e)
    {
      $response[&#34;success&#34;] = 0;
      $response[&#34;message&#34;] = &#34;error occured&#34;;
    }
}
?&gt;
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>坦率地说,查看您的 <code>NSLog</code> 结果,看起来服务器代码在 JSON 结果之后错误地返回了一些额外的 HTML(从 <code>&lt;script&gt;</code> 行开始) .查看 <code>$response</code> 的正文,它报告成功,但看起来响应中包含了一些额外的文本,可能是 <code>push_order</code> 的结果,或者是一些 HTML在 <code>%></code> 之后,或者插入一些额外 HTML 的一些 Web 服务错误。</p>

<p>关注您的客户端请求代码,它应该设置 <code>Content-Type</code> 和 <code>Accept</code>header ,但这并不重要。但是设计良好的请求应该这样做。关键问题是 PHP 在输出 JSON 之前或之后应该不输出任何其他内容。</p>

<p>对于它的值(value),如果您的 Web 服务期待一个真正的 JSON 请求,我会建议对您的客户端代码进行一系列简化(除了设置这两个额外的 header 之外)。例如,只需将 <code>NSJSONSerialization</code> 的输出作为 <code>httpBody</code> 发送;不要拿那个<code>NSData</code>,把它转换成一个<code>NSString</code>,然后再把它转换回一个<code>NSData</code>。只需发送 <code>jsonData</code> 作为 <code>httpBody</code>:</p>

<pre><code>NSDictionary *tvarns = @{@&#34;order_cart&#34;: _order_cart};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tvarns
                                                   options:0
                                                   error:&amp;error];

// if you want to see the JSON, you can do this, but this is not needed
//
// NSString *order_cart = [ initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSLog(@&#34;%@&#34;,order_cart);

// none of this stuff is needed; at worst, it can introduce encoding problems; at best, it&#39;s inefficient to do all that stuff
//
// NSString *post = ;
// NSLog(@&#34;the data Details is %@&#34;, post);
// NSData *postData = ;
// //Next up, we read the postData&#39;s length, so we can pass it along in the request.
// NSString *postLength = ];

// Now that we have what we&#39;d like to post, we can create an NSMutableURLRequest, and include our jsonData

NSMutableURLRequest *request = [ init];

];
;

// you don&#39;t need this, because NSURLSession sets the length for you
//
// ;

// use the original jsonData here

;

// you should, if you&#39;re a good web-service citizen, set the header; it&#39;s not always needed, but it&#39;s advisable

// tell the server that you&#39;re sending JSON request

;

// tell the server that you&#39;re expecting JSON response

;

// Unless you need a new session for some reason, it&#39;s better to use the shared session

NSURLSession *session = ;

[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
      NSLog(@&#34;error: %@&#34;, error);
    }

    if (!data) {
      return;
    }

    NSError *parseError;
    NSDictionary *jsonDict = ; // you need to convert to dictionary object
    if (jsonDict) {
      NSLog(@&#34;requestReply: %@&#34;, jsonDict);
    } else {
      NSLog(@&#34;parseError: %@&#34;, parseError);
      NSLog(@&#34;response: %@&#34;, response); // when you have failure, it&#39;s sometimes useful to see what this says
      NSString *requestReply = [ initWithData:data encoding:NSUTF8StringEncoding]; // this is json string
      NSLog(@&#34;requestReply: %@&#34;, requestReply);
    }
}] resume];
</code></pre>

<p>再次,在提出这些简化建议后,我真的怀疑服务器代码中存在错误,包括 <code>&lt;script&gt;...</code> 之后的所有垃圾。我敢打赌,您的 Android 代码在响应结束时忽略了所有这些错误数据,而 <code>NSJSONSerialization</code> 正确指出响应在技术上不是格式正确的 JSON。 (顺便说一下,我上面的代码会正确记录 JSON 错误。)</p>

<hr/>

<p>查看您添加到修改后问题中的 PHP 代码,它正在抓取 <code>$order_cart=$_POST['order_cart'];</code>,这意味着您的 Web 服务需要一个 <code>x-www-form-urlencoded</code> 请求。然后,PHP 代码继续将 <code>$items</code> 定义为 <code>json_decode($order_cart,true)</code>,然后使用 <code>foreach</code> 迭代到 <code>$items[ 'order_cart']</code>。这意味着 Web 服务期待 <code>x-www-form-urlencoded</code> 请求,其与 <code>order_cart</code> 键关联的值本身就是一个由 <code>order_cart< 键控的 JSON 字典</code>(再次),即请求正文将类似于 <code>order_cart={"order_cart":[...]}</code>。 </p>

<p>这不是一个非常优雅的设计,但如果你坚持这样做,你将不得不创建 <code>x-www-form-urlencoded</code> 请求,其键是 <code>order_cart</code> ,其值为 <code>{"content-type":[...]}</code> 形式的 JSON 字典的百分比编码表示。</p>

<pre><code>NSDictionary *tvarns = @{@&#34;order_cart&#34;: _order_cart};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tvarns
                                                   options:0
                                                   error:&amp;error];
NSString *jsonString = [ initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *bodyString = ];

NSMutableURLRequest *request = [ initWithURL:];
;
];
;
;

// Unless you need a new session for some reason, it&#39;s better to use the shared session

NSURLSession *session = ;

[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
      NSLog(@&#34;error: %@&#34;, error);
    }

    if (!data) {
      return;
    }

    NSError *parseError;
    NSDictionary *jsonDict = ; // you need to convert to dictionary object
    if (jsonDict) {
      NSLog(@&#34;requestReply: %@&#34;, jsonDict);
    } else {
      NSLog(@&#34;parseError: %@&#34;, parseError);
      NSLog(@&#34;response: %@&#34;, response); // when you have failure, it&#39;s sometimes useful to see what this says
      NSString *requestReply = [ initWithData:data encoding:NSUTF8StringEncoding]; // this is json string
      NSLog(@&#34;requestReply: %@&#34;, requestReply);
    }
}] resume];
</code></pre>

<p>地点:</p>

<pre><code>@interface NSCharacterSet (URLQueryValue)

/**
Character set of characters allowed within value (or a key) in a application/x-www-form-urlencode key/value pair.

@return NSCharacterSet of allowed characters.
*/
+ (NSCharacterSet *) URLQueryValueAllowedCharacterSet;

@end

@implementation NSCharacterSet (URLQueryValue)

+ (NSCharacterSet *) URLQueryValueAllowedCharacterSet {
    static NSString * const generalDelimitersToEncode = @&#34;:#[]@&#34;; // does not include &#34;?&#34; or &#34;/&#34; due to RFC 3986 - Section 3.4
    static NSString * const subDelimitersToEncode = @&#34;!$&amp;&#39;()*+,;=&#34;;

    NSString * const characterToEncode = ;

    NSMutableCharacterSet *cs = [ mutableCopy];
    ;
    return cs;
}

@end
</code></pre>

<p>和</p>

<pre><code>@interface NSString (URLQueryValue)
/**
String percent encoding for key or value in key/value pair within an application/x-www-form-urlencoded request.

@return Percent encoded string.
*/
- (NSString *)stringByAddingPercentEncodingQueryValue;
@end

@implementation NSString (URLQueryValue)
- (NSString *)stringByAddingPercentEncodingQueryValue {
    return ];
}
@end
</code></pre>

<p>坦率地说,我建议更改 Web 服务以处理真正的 JSON 请求,而不是 <code>x-www-form-urlencoded</code> 请求中的 JSON。如果你这样做了,客户端代码看起来更像我上面的原始答案。但是对于您现有的 Web 服务代码,您需要创建类似于我的第二个代码示例的内容。</p></p>
                                   
                                                <p style="font-size: 20px;">关于php - 将方法 nsdictionary 发布到 json 对象 iOSobjective-c ,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/44800588/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/44800588/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: php - 将方法 nsdictionary 发布到 json 对象 iOS objective-c