HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://my.server:8080/android/service.php");


List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "getjson"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

service.php生成json字符串.我怎么才能从我的response里拿到呢?顺便说一句,我已经封锁了GSON库,也许我可以使用其中的任何方法呢?

与此类似的解决方案看起来相当丑陋,imo:best way to handle json from httpresponse android

There much be better ways, right?

Any help is appreciated, thanks


Update:

String json = EntityUtils.toString(response.getEntity());

看起来很管用.只有一个小问题:绳子用括号[]Package.我应该手动移除它们吗?它们是由php:s json_encode()生成的

推荐答案

我想你遇到的问题和我刚才遇到的类似.如果您运行:

String json_string = EntityUtils.toString(response.getEntity());
JSONObject temp1 = new JSONObject(json_string);

The above code will throw an exception and it looks like the JSON array brackets are to blame. But it's fine to have a JSON array as the top level element! You just need to use JSONArray() instead of JSONObject:

String json_string = EntityUtils.toString(response.getEntity());
JSONArray temp1 = new JSONArray(json_string);

因此,您必须知道,在JSON代码中,您是得到一个JSONArray还是一个作为JSONObject的字典.

如果你习惯了iOS/Objective-C JSON解析库,那么它们使用相同的顶级元素来处理JSON字典和JSON数组,因此转到JAVA/Android世界时,我很困惑,根据返回的顶级,有两种处理JSON的类型.

Json相关问答推荐

如何将加权边列表导出到JSON树?

Vega Lite中的图例对齐

如何创建可由Gin序列化到json的排序键值映射?

JQ如何获取特定子元素的所有父母

在Reaction中从JSON文件中筛选数组

如果主对象中已存在属性,则不应在Jolt中引用次对象

在Databricks中如何将JSON文件作为字典读取

jq :当路径可变时更新 json 内容

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

父键中的 Perl JSON 数组

如何使用 Google 表格应用程序脚本将 JSON 中的多个字段提取到 Google 表格中

在 JOLT 中重新排列值

在 postgresql 中将行转换为 json 对象

N1QL 聚合查询 Couchbase

缺少所需的请求正文内容:org.springframework.web.method.HandlerMethod$HandlerMethodParameter

JSON.NET 中特定对象的自定义转换

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

如何安装 json gem - 无法构建 gem 原生扩展(mac 10.10)

as_json 没有在关联上调用 as_json

log4j 支持 JSON 格式吗?