JSONObject 和 JSONArray 获取value 的方法
生活随笔
收集整理的這篇文章主要介紹了
JSONObject 和 JSONArray 获取value 的方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JSONObject 和 JSONArray 獲取value 值 主要是根據(jù)key 值來(lái)獲取的,使用方法是get() 或者getJSONObject 方法很簡(jiǎn)單
下面列舉幾個(gè)例子,大家可以參考下代碼
public class MainActivity extends AppCompatActivity {String data1 = "{\"age\":\"23\",\"hobby\":\"游戲\",\"name\":\"小牧\"}";String data2 = " [{\"age\":\"23\"},{\"hobby\":\"游戲\"},{\"name\":\"小牧\"}]";String data = "{\n"+ " \"home\":{\n"+ " \"name\":\"外灘\",\n"+ " \"address\":\"上海市黃浦區(qū)中山東一路(臨黃浦江)\",\n"+ " \"lat\":3123777,\n"+ " \"lng\":12149060\n"+ " },\n"+ " \"company\":{\n"+ " \"name\":\"華為研發(fā)中心\",\n"+ " \"address\":\"上海市浦東新區(qū)新金橋路2222號(hào)\",\n"+ " \"lat\":3126255,\n"+ " \"lng\":12163020\n"+ " }\n"+ "}";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);try {JSONObject jsonObject1 = new JSONObject(data1);Object age = jsonObject1.get("age");Object hobby = jsonObject1.get("hobby");Object name = jsonObject1.get("name");Log.e("------data1", "年齡=" + age + "愛(ài)好=" + hobby + "姓名=" + name);} catch (JSONException e) {e.printStackTrace();}try {JSONArray jsonArray = new JSONArray(data2);Log.e("--------jsonArray", jsonArray + "");JSONObject objectAge = jsonArray.getJSONObject(0);JSONObject objectHobby = jsonArray.getJSONObject(1);JSONObject objectName = jsonArray.getJSONObject(2);Object age = objectAge.get("age");Object hobby = objectHobby.get("hobby");Object name = objectName.get("name");Log.e("--------jsonArray_con", "年齡=" + age + "愛(ài)好=" + hobby + "姓名=" + name);} catch (JSONException e) {e.printStackTrace();}try {JSONObject jsonObject = new JSONObject(data);JSONObject homeObj = jsonObject.getJSONObject("home");String homeName = String.valueOf(homeObj.get("name"));String homeAdress = String.valueOf(homeObj.get("address"));String homelat = String.valueOf(homeObj.get("lat"));String homelng = String.valueOf(homeObj.get("lng"));Log.e("----home","homeName=" + homeName + "homeAdress=" + homeAdress + "homeLat=" +homelat +"homeLng=" + homelng);JSONObject companyObj = jsonObject.getJSONObject("company");String companyName = String.valueOf(companyObj.get("name"));String companyAddress = String.valueOf(homeObj.get("address"));String companylat = String.valueOf(homeObj.get("lat"));String companylng = String.valueOf(homeObj.get("lng"));Log.e("------company","companyName=" + companyName + "companyAddress=" + companyAddress +"companylat=" + companylat + "companylng=" + companylng);} catch (JSONException e) {e.printStackTrace();}}
}
打印的log
如果想動(dòng)態(tài)獲取key 和 value 可以參考我之前寫的
json 動(dòng)態(tài)獲取key 和value
總結(jié)
以上是生活随笔為你收集整理的JSONObject 和 JSONArray 获取value 的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android 内容观察者 Conten
- 下一篇: 育婴师多少钱一个月啊?