json的存在有三种结构:
对象:{"name":"LiLei","age":25}
数组:比如:[{"name":"LiLei","age":25},{"name":"Tom","age":25}]
值:{"name":"LiLei", "birthday":{"month":8,"day":26}},类似于对象嵌套对象.
一、
1.简单的解析json字符串——根据json中的键得到它的值
String name = jsonObject.getString("name");
int num = jsonObject.getInt("age");
2.将json字符串转换为java对象
JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
Person jb = (Person)JSONObject.toBean(obj,Person.class);//将建json对象转换为Person对象
3.将java对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象
String str = json.toString();//将json对象转换为字符串
二、json 与常见的类型之间的转换
//list转json
List list=new ArrayList();
list.add("1");
list.add("2");
JsonArray json=JsonArray.fromObject(list)
//map转json
Map map = new HashMap();
map.put("欧尼", "json");
map.put("听我", Boolean.TRUE);
map.put("three", new Integer(1));
JSONObject json = JSONObject.fromObject(map);
//Bean转成json代码
JsonBean jb=new JsonBean()
JSONObject jsonObject = JSONObject.fromObject(jb);
//数组转json
int [] arr = new int[] { 1,2,3};
JSONArray jsonarray = JSONArray.fromObject(arr);
//字符串转json
JSONArray jsonarr = JSONArray.fromObject("['json','is','easy']" );
String jsonStr = "{\"id\": 2," +
" \"title\": \"json title\", " +
"\"config\": {" +
"\"name\": 34," +
"\"type\": 35," +
"}, \"class\": [" +
"\"one\", \"two\", \"three\"" +
"]}";
//转换成为JSONObject对象
JSONObject jsonObj = new JSONObject(jsonStr);