Java处理JSON对象

需要导入的jar包:
beanutils.jar
collections.jar
lang.jar
logging.jar
ezmorph.jar
json-lib.jar
实例代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Test {
    public static void main(String[] args) {
        User user = new User("admin", "adminpsd");
        //JavaBean 转JSON
        System.out.println(JSONObject.fromObject(user));
        //字符串转JSONObject
        String jstr = "{\"password\":\"adminpsd\",\"username\":\"admin\"}";
        JSONObject obj = JSONObject.fromObject(jstr);
        System.out.println(obj.getString("username"));
        System.out.println(obj.getString("password"));
        //JSONObject转JavaBean
        System.out.println(JSONObject.toBean(obj, User.class));
        //JavaBean转JSONArray
        List<User> list = new ArrayList<>();
        for(int i =0;i<3;i++){
            list.add(new User("user"+i, "psd"+i));
        }
        System.out.println(JSONArray.fromObject(list));
        String jsonArray = "[{\"password\":\"psd0\",\"username\":\"user0\"},{\"password\":\"psd1\",\"username\":\"user1\"},{\"password\":\"psd2\",\"username\":\"user2\"}]";
        JSONArray ja = JSONArray.fromObject(jsonArray);
        for (int i = 0; i < ja.size(); i++) {
            System.out.println(ja.getJSONObject(i).get("username"));
        }
        //JSONArray转JavaBean
    System.out.println(Arrays.toString((User[])JSONArray.toArray(ja,User.class)));
    }
    public static class User{
        String username;
        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;
        }
        public User(String username, String password) {
            super();
            this.username = username;
            this.password = password;
        }
        //无参构造函数是JavaBean的基本要求,因为反射时通过无参构造函数创建新对象
        public User() {
            super();
        }
        @Override
        public String toString() {
            return "User [username=" + username + ", password=" + password + "]";
        }

    }
}
    1.

你可能感兴趣的:(java,json)