使用fastjson

tech2025-03-06  16

package cn.alan; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * fastjson的使用 */ public class Main { public static void main(String[] args) { /** * 1、将JSON串转为Java对象 */ String jsonStr="{'userName':'root','password':'123456'}"; User javaObject=JSON.parseObject(jsonStr, User.class); //root System.out.println(javaObject.getUserName()); //123456 System.out.println(javaObject.getPassword()); /** * 2、Java对象转为JSON字符串 */ User user =new User("user","user123"); String userJson=JSON.toJSONString(user); //{"password":"user123","userName":"user"} System.out.println(userJson); /** * 3、JSON字符串转为JSONArray对象,再从JSONArray中取出JSONObject */ String jsonStr3 = "[{\"password\":\"123\",\"userName\":\"张三\"},{\"password\":\"321\", \"userName\":\"李四\"}]"; JSONArray jsonArray=JSON.parseArray(jsonStr3); for (int i = 0; i < jsonArray.size(); i++) { JSONObject object=jsonArray.getJSONObject(i); // String userName=object.getString("userName"); String password=object.getString("password"); //张三---123 //李四---321 System.out.println(userName+"---"+password); } /** * 4、JSON字符串转为JSONObject,再将JSONObject转为Java对象 */ String json4="{'userName':'json4','password':'123'}"; JSONObject jsonObject4=JSONObject.parseObject(json4); User user4= JSONObject.toJavaObject(jsonObject4, User.class); //json4---123 System.out.println(user4.getUserName()+"---"+user4.getPassword()); } } package cn.alan; /** * 测试使用的JavaBean * @version 1.0 * @date 2020/9/4 0:46 */ public class User { private String userName; private String password; public User() { } public User(String userName, String password) { this.userName = userName; this.password = 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 "User{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + '}'; } }
最新回复(0)