第一種用Android自帶的 org.Json包
package Test.action;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//用之前先把org.json包裏面的類 全部放到項目裏
public class TestJson {
public static void main(String[] args) throws JSONException {
String str1 = "{name:'wangyafei',age:'20',sex:'man',fav:{1:'money',2:'money too'}}";
JSONObject jsonObject = new JSONObject(str1);
System.out.println(jsonObject.get("name"));
System.out.println(jsonObject.get("age"));
JSONObject fav = jsonObject.getJSONObject("fav");
System.out.println(fav.get("1"));
System.out.println(fav.get("2"));
jsonObject.put("add", "mafang");
System.out.println(jsonObject.toString());
// -----------------------------------------------------------------------------------
String str2 = "[{name:'wangyafei'},{age:'20',sex:'woman'},{sex:'man'},{fav:'money'}]";
JSONArray array = new JSONArray(str2);
System.out.println(array.length());
System.out.println(array.getJSONObject(0).get("name"));
System.out.println(array.getJSONObject(1).get("sex"));
//for(int i = 0; i < array.length(); i++){
//JSONObject object = array.getJSONObject(i);
// 它是可以遍歷的
//}
}
}
第二種,用google的Gson包
解析
import com.google.gson.stream.JsonReader;
String jsonData = "[{\"title\":\"西紅柿\",\"num\":50,\"unit\":\"公斤\"},{\"title\":\"洋蔥\",\"num\":50,\"unit\":\"公斤\"}]";
JsonReader reader=new JsonReader(new StringReader(jsonData));
reader.beginArray();
while(reader.hasNext())
{
reader.beginObject();
while(reader.hasNext())
{
String name=reader.nextName();
if(name.equals("title"))
Log.e("title", reader.nextString()) ;
else if(name.equals("num"))
Log.e("num",reader.nextInt()+"");
else if(name.equals("unit"))
Log.e("unit", reader.nextString());
}
reader.endObject();
}
reader.endArray();
}
List轉Json
List<String> testList=new ArrayList<String>();
testList.add("你好");
testList.add("我好");
testList.add("大家好");
Gson gson=new Gson();
String jsonStr=gson.toJson(testList);
System.out.prrintln(jsonStr);
輸出結果爲
12-10 06:27:41.484: I/System.out(482): ["你好","我好","大家好"]
List<Map<String,Object>>轉Json
List<Map<String,Object>> testList=new ArrayList<Map<String,Object>>();
Map<String,Object> map=new HashMap<String, Object>();
map.put("title", "豆子");
map.put("num", 20);
map.put("unit", "公斤");
testList.add(map);
map=new HashMap<String, Object>();
map.put("title", "大米");
map.put("num", 30);
map.put("unit", "公斤");
testList.add(map);
map=new HashMap<String, Object>();
map.put("title", "西紅柿");
map.put("num", 40);
map.put("unit", "公斤");
testList.add(map);
Gson gson=new Gson();
String jsonStr=gson.toJson(testList);
System.out.println(jsonStr);
輸出結果爲:
12-10 06:44:10.764: I/System.out(568): [{"unit":"公斤","num":20,"title":"豆子"},{"unit":"公斤","num":30,"title":"大米"},{"unit":"公斤","num":40,"title":"西紅柿"}]