如何使用JSON从iPhone应用程序将对象数组发送到PHP脚本

问题描述:

我有一个iPhone应用程序,其中包含要发送到PHP脚本的对象数组,并将它们存储在mySQL数据库中.数组中的对象仅包含浮点和字符串,没有什么特别的.

I have an iPhone app with an array of objects that I want to send to a PHP script and have them be stored in a mySQL database. The objects in the array contain only floating points and strings, nothing special.

据我了解,将数组发送到php脚本的最佳方法是将数组转换为JSON,通过http post将其发送到php脚本,然后在另一端执行json_decode.但是我很难弄清楚如何将数组转换为json对象.

From what I understand the best way to send the array to the php script is to convert the array into an JSON, send it to the php script via http post, and do a json_decode on the other end. However I'm having a hard time figuring out how to convert the array into a json object.

有人可以给我一个从哪里开始的指针吗?

Can someone give me a pointer of where to start?

从Objective-c的JSON库开始:

Start with the JSON library for objective-c:

http://code.google.com/p/json-framework

这将使序列化更加容易,因为它具有将NSArray转换为JSON的方法.

That will make the serialization much easier, as it has a method to convert an NSArray to JSON.

http://json-framework.googlecode.com /svn/trunk/documentation/interfaceSBJSON.html#830175bff0fbef8ccb82da852a154b48

您可以从那里使用不同的机制发布信息,但是NSURLConnection是最简单的. 您可以根据需要进行同步或异步.

From there you can post using different mechanisms, but NSURLConnection is the easiest. You can do synch or asynch, depending on your needs.

您需要在json请求上设置一些标头:

You will need to set some headers on the request for json:

NSMutableURLRequest * r = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
[r addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[r setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];