zoukankan      html  css  js  c++  java
  • org.json库下的json的基本使用

    public class Users {

    private String username;
    private String password;
    public String getUsername() {
    return username;
    }
    public void setUsername(String username) {
    this.username = username;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    @Override
    public String toString() {
    return "{"username":"" + username + "", "password":"" + password + ""}";
    }
    }

    package com.huawei.test;

    import java.util.HashMap;
    import java.util.Map;

    import org.json.JSONArray;
    import org.json.JSONObject;

    public class TestJson {

    public static void main(String[] args) {


    /**
    * 将json字符串转换为 json对象
    */
    //构建json字符串
    String json = "{"username":"lisi","password":"123123","address":{"province":"四川"},"fav":[{"name":"read"},{"name":"eat"},{"name":"run"}]}";
    //
    //Object obj = JSONObject.stringToValue(json);
    //通过构造器去构造json的实例
    JSONObject jsonObject = new JSONObject(json);
    //System.out.println(obj);
    //得到对应键的值
    System.out.println(jsonObject.get("username"));
    System.out.println(jsonObject.getString("password"));
    //得到json对象中的另一个对象
    System.out.println(jsonObject.getJSONObject("address").get("province"));
    //得到一个数组
    JSONArray array = jsonObject.getJSONArray("fav");
    //得到数组里面的值 有可能是基本值 有可能是对象
    JSONObject o = array.getJSONObject(0);
    System.out.println(o.get("name"));



    Users users = new Users();
    users.setUsername("zhangsan");
    users.setPassword("123123123");
    //必须重写toString方法 并返回构建的json字符串


    Map<String, Object> map = new HashMap<String, Object>();
    map.put("username", "testmap");
    map.put("email", "test@test.com");

    String str = JSONObject.valueToString(users);
    System.out.println(str);

    System.out.println(JSONObject.valueToString(map));

    }
    }

  • 相关阅读:
    LF.51.Insert In Binary Search Tree
    Use Array To Implement Queue With Size(bounded)
    Use LinkedList to implement Queue
    Use LinkedList to Implement Stack
    LT.11.Search Range In Binary Search Tree
    Odoo 12开发之后台视图 – 设计用户界面 ###
    Odoo 之业务逻辑
    Odoo开发之记录集 – 使用模型数据
    odoo 之 结构化应用数据
    odoo之数据导入导出以及模块数据
  • 原文地址:https://www.cnblogs.com/hwgok/p/5843062.html
Copyright © 2011-2022 走看看