• Java解析Json数据的两种方式


    JSON数据解析的有点在于他的体积小,在网络上传输的时候可以更省流量,所以使用越来越广泛,下面介绍使用JsonObject和JsonArray的两种方式解析Json数据。

    使用以上两种方式解析json均需要依赖json-lib.jar开发包使用依赖包

    1、JsonObject

    使用JsonObject解析只有一条数据的json是非常方便的例如:"{"name":"zhangsan","password":"zhangsan123","email":"10371443@qq.com"}"

    public static void main(String[] args) {  
      
             String jsonString ="{"name":"zhangsan","password":"zhangsan123","email":"10371443@qq.com"}";  
             JSONObject json = JSONObject.fromObject(jsonString);  
             User user = new User();  
             user.setName(json.getString("name"));  
             user.setPassword(json.getString("password"));  
             user.setEmail(json.getString("email"));  
             System.out.println(user.toString());  
        }  

    2、JsonArray

    使用JsonArray解析数组数据的json是非常方便的例如:"[{"name":"zhangsan","password":"zhangsan123","email":"10371443@qq.com"},{"name":"lisi","password":"lisi123","email":"1435123@qq.com"}]"

    String json ="[{"name":"zhangsan","password":"zhangsan123","email":"10371443@qq.com"},{"name":"lisi","password":"lisi123","email":"1435123@qq.com"}]";  
             JSONArray jsonArray = JSONArray.fromObject(json);  
             ArrayList<User> users = new ArrayList<User>();  
             for (int i = 0; i < jsonArray.size(); i++) {  
                 User userM = new User();  
                 user.setName(jsonArray.getJSONObject(i).getString("name"));  
                 user.setpassword(jsonArray.getJSONObject(i).getString("password"));  
                 user.setEmail(jsonArray.getJSONObject(i).getString("email"));  
                 users.add(user);  
            }  
             for (User user : users) {  
                System.out.println(user.toString());  
            }  
  • 相关阅读:
    centos crash debug
    go get Unknown SSL protocol error in connection to gopkg.in
    Tensorflow serving with Kubernetes
    Spring 集成 Swagger UI
    Docker Registry V2 Garbage Collection
    Docker Registry V2 with Nginx
    Zabbix磁盘性能监控
    Zabbix CPU utilization监控参数
    Windows挂载Gluster复制卷
    Redis持久化存储(三)
  • 原文地址:https://www.cnblogs.com/hq233/p/8616654.html
Copyright © 2020-2023  润新知