1.内置Json
private String json0 = "{\"name\":\"hello json\"}"; private String jsonArray1 = "{\"query\":\"Pizza\",\"locations\":[94043,90210]}"; private String jsonArray2 = "{\"number\":[[zhangsan,133],[lisi,3234]]}"; private String jsonArray3 = "{\"mobile\":[{\"name\":\"android\"},{\"name\":\"iphone\"}]}"; try { JSONObject demoJson = new JSONObject(json0); String name = (String) demoJson.get("name"); Log.i("name-->value:", name); JSONObject demoJson1 = new JSONObject(jsonArray1); String query = demoJson1.getString("query"); Log.i("query-->value:", query); JSONArray locationArray = demoJson1.getJSONArray("locations"); for (int i = 0; i < locationArray.length(); i++) { Log.i("location-->value:", String.valueOf(locationArray.getInt(i))); } JSONObject demoJson2 = new JSONObject(jsonArray2); JSONArray array = demoJson2.getJSONArray("number"); for (int i = 0; i < array.length(); i++) { JSONArray tmp = array.getJSONArray(i); Log.i("嵌套数组-->value:", tmp.getString(0) + tmp.getInt(1)); } JSONObject demoJson3 = new JSONObject(jsonArray3); JSONArray array1 = demoJson3.getJSONArray("mobile"); for(int i =0;ivalue:",innername); }
2. Gson
package com.cmdi.layout;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import java.util.ArrayList;import java.util.List;/** * https://github.com/google/gson * * https://github.com/google/gson/blob/master/UserGuide.md * * Created by 1 on 2016/4/17. */public class GsonDemo { public static void testGson() { String json = "{\"name\":\"lili\",\"age\":18}"; Gson gson = new Gson(); Person person = gson.fromJson(json, Person.class); System.out.println(person.getName()); ArrayListpersons = new ArrayList<>(); Person per = new Person(); per.setAge(13); persons.add(per); String list2Josn = gson.toJson(persons); System.out.println(list2Josn); String s = "[{\"name\":\"lili\",\"age\":18},{\"name\":\"go\",\"age\":222}]"; List retList = gson.fromJson(s, new TypeToken
>() { }.getType()); System.out.println(retList.get(0).getName()); System.out.println(retList.size()); }}