• Java中的json数据类型操作


    package com.ss1.json;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class JsonParse {
    
        public static void main(String[] args) throws JSONException {
             //接收到的JSON字符串
            String result = "[{"username" : "yourname","nickname" : "yournickname"}]";
            //根据字符串生成JSON对象
            JSONArray json = new JSONArray(result);
            JSONObject resultJson = json.optJSONObject(0);
            
             //获取数据项
            String username = resultJson.getString("username");
            System.out.println(username);
            
            
             String jsonStr = "{"id": 2," + 
                        " "title": "json title", " + 
                        ""config": {" +
                            ""width": 34," +
                            ""height": 35," +
                        "}, "data": [" +
                            ""JAVA", "JavaScript", "PHP"" +
                        "]}";
             
            //创建JSONObject对象
             JSONObject jsonObject = new JSONObject(jsonStr);
             System.out.println(jsonObject.getInt("id"));
             System.out.println(jsonObject.getString("title"));
             
             JSONObject config = jsonObject.getJSONObject("config");
             System.out.println(config.getInt("width"));
             
             //向json中添加数据
             JSONObject json1 = new JSONObject();
             json1.put("username", "cmy");
             json1.put("height", 172);
             json1.put("age", 23);
             
            //创建JSONArray数组,并将json添加到数组
             JSONArray jsonArray1 = new JSONArray();
             jsonArray1.put(json1);
            //转换为字符串
             System.out.println(jsonArray1.toString());
             
            //初始化ArrayList集合并添加数据
             List<String> list = new ArrayList<String>();
             list.add("username");
             list.add("age");
             list.add("sex");
             
            //初始化HashMap集合并添加数组
             Map map = new HashMap<>();
             map.put("bookname","css/html");
             map.put("price","42.0");
             
            //初始化JSONArray对象,并添加数据
             JSONArray array = new JSONArray();
             array.put(list);
             array.put(map);
             System.out.println(array);
        }
    }
  • 相关阅读:
    Teacher Bo HDU 5762(暴力)
    The Unique MST POJ1679(次小生成树)
    Sqrt Bo hdu 5752
    Borg Maze POJ 3026(BFS+最小生成树)
    Highways POJ 1751(最小生成树)
    hdu---2050---折线分割平面
    POj---1469---Courses
    poj---2349---Arctic Network
    poj-2528-Mayor's posters
    POJ---3468---A Simple Problem with Integers
  • 原文地址:https://www.cnblogs.com/tingbogiu/p/5757579.html
Copyright © 2020-2023  润新知