【发布时间】:2011-03-03 13:59:32
【问题描述】:
我应该在 android 中开发一个程序,它将 .json 文件上传到 web 服务并以 .json 格式取回响应并解析它。谁能告诉我如何上传 json 文件和任何需要 .json 文件、验证它并返回 .json 文件的网络服务?谢谢。
【问题讨论】:
我应该在 android 中开发一个程序,它将 .json 文件上传到 web 服务并以 .json 格式取回响应并解析它。谁能告诉我如何上传 json 文件和任何需要 .json 文件、验证它并返回 .json 文件的网络服务?谢谢。
【问题讨论】:
理想的设置是
Android 应用程序 GAE
如果您需要网络服务来检查您的 json 文件...只需将服务器上的 json 内容读取到 JSON 对象中,如果没有抛出异常,您最好使用对客户端的响应。
我提供了两边都使用 Restlet (restlet.org) 的代码。
Android 应用
Client client = new Client(Protocol.HTTP);
Request req = new Request();
req.setMethod(Method.POST); // can be Method.GET
req.setResourceRef(new Reference(/* SERVER URL */+ "/jsonservice"));
req.getCookies().add(GAuth.getCookie());
/* Build your JSONObject */
req.setEntity(/* JSONObject */.toString(), MediaType.APPLICATION_JSON);
req.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.APPLICATION_JSON));
Response resp = client.handle(req);
if (resp.getStatus() == Status.SUCCESS_OK)
{
// resp.getEntity().getText() -> The JSON string returned by GAE
JSONObject jo=new JSONObject(resp.getEntity().getText());
/* Use your JSON object */
}
GAE 应用
GAE:战争/WEB-INF/web.xml
<!-- Servlets --> <servlet> <servlet-name>MyApplication</servlet-name> <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class> <init-param> <param-name>org.restlet.application</param-name> <param-value>com.mypackage.MyApplication</param-value> </init-param> </servlet> <!-- Servlet Mappings --> <servlet-mapping> <servlet-name>MyApplication</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
Restlet : MyApplication.java
package com.mypackage; public class MyApplication extends Application { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/jsonservice", MyJsonService.class); return router; } }
Restlet : MyRouter.java
package com.mypackage; public class MyJsonService extends ServerResource { @Post("json:json") // can be @Get("json") public Representation jsonProcessor(Representation entity) { Representation resp = null; JSONObject req = (new JsonRepresentation(entity)).getJsonObject(); /* Do Someting with the JSON object ..... ..... ..... Build your JSON response object. You will use this object below. */ setStatus(Status.SUCCESS_OK); resp = new JsonRepresentation(/* JSONObject */.toString()); return resp; } }
【讨论】:
上传 json 文件与上传任何其他文件类型没有区别。有一个例子here。它解释了如何将文件上传到 php 服务器。
并且http://json.org/ 有一个java 库,您可以使用它来创建/解析json 对象。 正如下面的评论所指出的,android 中包含一个json 库。
【讨论】: