json的数据格式(仔细查看)
1.json对象就是jsonObject,jsonobject里可以放入很多键值对,并以逗号为分隔符。
jsonObject里还可以嵌套JsonObject对象,或者数组信息作为value,数组作为key的velue时,要以中括号包起来。即:“array”:【“1”,“2”,“3”】,
3.怎样将key value放入jsonObject里?:用jsonObject的put方法,和element方法。element方法用于放入数组或者jsonObject。
4.json字符串,比如
- String jsonString = "{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}";
- /* 将Json字符串转为java对象 */
- JSONObject obj = JSONObject.fromObject(jsonString);
5.5.理解Json的关键在于,在于区别json字符串和json对象,json对象可以转换为json字符串,json字符串可以转换为json对象。
6.5.理解Json的关键在于,在于区别json字符串和json对象,json对象可以转换为json字符串,json字符串可以转换为json对象。
5.理解Json的关键在于,在于区别json字符串和json对象,json对象可以转换为json字符串,json字符串可以转换为json对象。Jsonobject就是json的java对象。
6.Jsonobject就是json的java对象。
4.解析jsonObject,
- /* 组装一个复杂的JSONArray */
- JSONObject jsonObject2 = new JSONObject();
- jsonObject2.put("UserName", "ZHULI");
- jsonObject2.put("age", "30");
- jsonObject2.put("workIn", "ALI");
- jsonObject2.element("Array", arrayList);
- jsonObject2.element("Object", jsonObject);
- System.out.println("jsonObject2:" + jsonObject2);
- }
- }
结果:
- jsonObject1:{"workIn":"ALI","age":"30","UserName":"ZHULI"}
- jsonObject2 FROM HASHMAP:{"workIn":"ALI","age":"30","UserName":"ZHULI"}
- jsonArray1:["ZHULI","30","ALI"]
- jsonArray2 FROM ArrayList:["ZHULI","30","ALI"]
- jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}]
- jsonObject2:{"workIn":"ALI","age":"30","Array":["ZHULI","30","ALI"],"UserName":"ZHULI","Object":{"workIn":"ALI","age":"30","UserName":"ZHULI"}
- 解析json
- public class Test {
- public static void main(String[] args) {
- String jsonString = "{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}";
- /* 将Json字符串转为java对象 */
- JSONObject obj = JSONObject.fromObject(jsonString);
- /* 获取Object中的UserName */
- if (obj.has("UserName")) {
- System.out.println("UserName:" + obj.getString("UserName"));
- }
- /* 获取ArrayObject */
- if (obj.has("Array")) {
- JSONArray transitListArray = obj.getJSONArray("Array");
- for (int i = 0; i < transitListArray.size(); i++) {
- System.out.print("Array:" + transitListArray.getString(i) + " ");
- }
- }
- }
- }