在Android中解析嵌套的JSONObject [重复]

Posted

技术标签:

【中文标题】在Android中解析嵌套的JSONObject [重复]【英文标题】:Parsing nested JSONObject in Android [duplicate] 【发布时间】:2015-07-05 12:24:38 【问题描述】:

在我的项目中,我从 HTTP 响应中获取了以下 JSON。

"base":"USD","date":"2015-04-24","rates":"AUD":1.2827,"BGN":1.8069,"BRL":2.9733,"CAD":1.2119,"CHF":0.9551,"CNY":6.1948,"CZK":25.364,"DKK":6.8927,"GBP":0.6614,"HKD":7.75,"HRK":7.0284,"HUF":278.53,"IDR":12954.0,"ILS":3.9244,"INR":63.563,"JPY":119.51,"KRW":1078.25,"MXN":15.358,"MYR":3.5741,"NOK":7.8298,"NZD":1.3216,"php":44.281,"PLN":3.7076,"RON":4.08,"RUB":51.215,"SEK":8.6674,"SGD":1.3375,"THB":32.55,"TRY":2.7314,"ZAR":12.182,"EUR":0.9239

我想从上面的 json 中获取“BGN”。如何获得。

【问题讨论】:

试试这个:***.com/questions/9605913/… 【参考方案1】:

这涉及多个步骤

首先:创建一个jsonObject

JSONObject jObject = new JSONObject(yourJSON_String);

第二:获取你想要的对象或数组,在你的情况下

obj =  getJSONObject("rates")

第三:获取所需的字符串

obj.getString("BGN");

这里是JSON CLASS REFERENCE

【讨论】:

【参考方案2】:

假设您使用的是 JSONObject,并且您的根文档称为“doc”,

JSONObject rates = doc.getJSONObject("rates") 将为您提供费率部分:

"AUD":1.2827,"BGN":1.8069,"BRL":2.9733,"CAD":1.2119,"CHF":0.9551,"CNY":6.1948,"CZK":25.364,"DKK":6.8927,"GBP":0.6614,"HKD":7.75,"HRK":7.0284,"HUF":278.53,"IDR":12954.0,"ILS":3.9244,"INR":63.563,"JPY":119.51,"KRW":1078.25,"MXN":15.358,"MYR":3.5741,"NOK":7.8298,"NZD":1.3216,"PHP":44.281,"PLN":3.7076,"RON":4.08,"RUB":51.215,"SEK":8.6674,"SGD":1.3375,"THB":32.55,"TRY":2.7314,"ZAR":12.182,"EUR":0.9239

从此对象中,您可以使用

简单地获取 BGN 值

String bgn = rates.getString("BGN")

【讨论】:

【参考方案3】:
JSONObject responseJson = new JSONObject("<your-string">);
JSONObject ratesJson = responseJson.getJSONObject("rates");
double rate = ratesJson.getDouble("BGN");

要清楚地看到JSON 对象,请使用PrettyJson。在此处复制粘贴 JSON 字符串,它将显示嵌套对象(如果有),以便清楚地理解响应。

【讨论】:

以上是关于在Android中解析嵌套的JSONObject [重复]的主要内容,如果未能解决你的问题,请参考以下文章

从android解析jsonObject并在webservice vb.net中获取它

Android JSON解析字符串无法转换为jsonobject

Android 中解析 JSON

Android中解析JSON格式数据常见方法合集

反序列化多层嵌套json实体

在 Android 中解析嵌套的 JSON 对象