JavaWeb——Java中JSON字符串与Java对象的互转

JavaWeb——Java中JSON字符串与Java对象的互转,第1张

JavaWeb——Java中JSON字符串与Java对象的互转 JSON数据和Java对象的相互转换
JSON解析器:
		常见的解析器:Jsonlib,Gson,fastjson,jackson
	1. Java对象转换JSON
		1. 使用步骤:
			1. 导入jackson的相关jar包
			2. 创建Jackson核心对象 ObjectMapper
			3. 调用ObjectMapper的相关方法进行转换
				1. 转换方法:
					writevalue(参数1,obj):
	                    参数1:
	                        File:将obj对象转换为JSON字符串,并保存到指定的文件中
	                        Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
	                        OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
	                writevalueAsString(obj):将对象转为json字符串

				2. 注解:
					1. @JsonIgnore:排除某个属性不要转换成JSON,给类的属性上加上这个注解。
					2. @JsonFormat:属性值得格式化日期字符串,取的是默认时区的时间
						@JsonFormat(pattern = "yyyy-MM-dd")
						   private Date birthday;
						   
						 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")//给默认时区加上8个小时
					3.指定转换json字符串是的别名 @JsonProperty("username")	 
					 @JsonProperty("username")
    				 private String name;
    				 
    				4. 如果该字段的值是null,就不会转换成JSON
    				 @JsonInclude(JsonInclude.Include.NON_NULL) //如果该字段的值是null,就不会转换成JSON
    				  private Long num; //null
				3. 复杂java对象转换
					1. List:数组
					2. Map:对象格式一致
					
	2. JSON转为Java对象
		1. 导入jackson的相关jar包
		2. 创建Jackson核心对象 ObjectMapper
		3. 调用ObjectMapper的相关方法进行转换
			1. readValue(json字符串数据,Class)				

Ajax的应用:校验用户名是否存在
	1. 服务器响应的数据,在客户端使用时,要想当做json数据格式使用。有两种解决方案:
		1. $.get(type):将最后一个参数type指定为"json"
		2. 在服务器端设置MIME类型
			response.setContentType("application/json;charset=utf-8");
			//设置跨域请求
			response.setHeader("Access-Control-Allow-Origin","*");
1.普通截取字符串方法将JSON字符串转换成Java对象

主方法MyTest

public class  MyTest {
    public static void main(String[] args) {
        //前台给后台提交的数据,常见的有两种格式
        // username=zhangsan&password=123456&age=23
        //{"username":"张三","password":"123456"}
        //把json字符串转换成java对象
        String jsonStr = "{"username":"张三","password":"123456"}";
        String s = jsonStr.replaceAll("[{}"]", "");
        System.out.println(s);
        String[] strings = s.split(",");
        System.out.println(strings[0]);
        System.out.println(strings[1]);
        
        String[] a = strings[0].split(":");
        System.out.println(a[0]);
        System.out.println(a[1]);
        
        String[] b = strings[1].split(":");
        System.out.println(b[0]);
        System.out.println(b[1]);
        
        User user = new User();
        user.setUsername(a[1]);
        user.setPasswrod(b[1]);
        
        System.out.println(user);
    }
}

对象User

public class User {
    private String username;
    private String passwrod;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPasswrod() {
        return passwrod;
    }
    public void setPasswrod(String passwrod) {
        this.passwrod = passwrod;
    }
    @Override
    public String toString() {
        return "User{" +
                "username='" + username + ''' +
                ", passwrod='" + passwrod + ''' +
                '}';
    }
}
2.java对象转成json字符串(保存到文件) 普通转换(String jsonStr = “{“username”:“张三”,“password”:“123456”}”;)
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class MyTest {
    public static void main(String[] args) throws IOException {
        //Java对象转换成JSON字符串
        //String jsonStr = "{"username":"张三","password":"123456"}";
        User user = new User("王五", "123456", 20, "18856259632");
        Car car = new Car();
        car.setCarName("宝马");
        car.setCarPrice(888888.0);
        //user.setCar(car);
        ArrayList list = new ArrayList<>();
        list.add("张曼玉");
        list.add("王祖贤");
        user.setGirlfriend(list);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writevalueAsString(user);
        System.out.println(jsonStr);
        //{"username":"王五","password":"123456","age":20,"phoneNum":"18856259632",car:{carName:"宝马",carPrice:8888},girlfriend:["刘亦菲","张曼玉"]}
        //把转好的数据保存到文件中
        mapper.writevalue(new File("a.json"), user);
    }
}
数组嵌套json( [{},{},{}] )
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        //[{},{},{}]
        User user1 = new User("王五", "12345685", 20, "18856259632");
        User user2 = new User("赵六", "12345685", 28, "18856259632");
        User user3 = new User("田七", "12345776", 24, "18856259632");
        ArrayList list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writevalueAsString(list);
        System.out.println(s);
        //把转好的数据保存到文件中
        mapper.writevalue(new File("b.json"), list);
    }
}
{“user1”:{},“user2”:{},“user3”:{}}
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class MyTest3 {
    public static void main(String[] args) throws IOException {
        //{"user1":{},"user2":{},"user3":{}}
        User user1 = new User("王五", "12345685", 20, "18856259632");
        User user2 = new User("赵六", "12345685", 28, "18856259632");
        User user3 = new User("田七", "12345776", 24, "18856259632");
        HashMap hm = new HashMap<>();
        hm.put("user1", user1);
        hm.put("user2", user2);
        hm.put("user3", user3);
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writevalueAsString(hm);
        System.out.println(s);
        //把转好的数据保存到文件中
        mapper.writevalue(new File("c.json"), hm);
    }
}

所用到的car类和user类

public class Car {
    private String carName;
    private Double carPrice;
    public String getCarName() {
        return carName;
    }
    public void setCarName(String carName) {
        this.carName = carName;
    }
    public Double getCarPrice() {
        return carPrice;
    }
    public void setCarPrice(Double carPrice) {
        this.carPrice = carPrice;
    }
    @Override
    public String toString() {
        return "Car{" +
                "carName='" + carName + ''' +
                ", carPrice=" + carPrice +
                '}';
    }
}
import java.util.List;

public class User {
    private String username;
    private String password;
    private int age;
    private String phoneNum;
    private Car car;
    private List girlfriend;
    public User() {
    }
    public User(String username, String password, int age, String phoneNum) {
        this.username = username;
        this.password = password;
        this.age = age;
        this.phoneNum = phoneNum;

    }

    public User(String username, String password, int age, String phoneNum, Car car, List girlfriend) {
        this.username = username;
        this.password = password;
        this.age = age;
        this.phoneNum = phoneNum;
        this.car = car;
        this.girlfriend = girlfriend;
    }
    public List getGirlfriend() {
        return girlfriend;
    }
    public void setGirlfriend(List girlfriend) {
        this.girlfriend = girlfriend;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getPhoneNum() {
        return phoneNum;
    }
    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }
}
3.Java对象转换成json字符串
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Date;

public class MyTest {
    public static void main(String[] args) throws JsonProcessingException {
        User user = new User();
        user.setUsername("zhangsan");
        user.setAge(12);
        user.setPassword("999999");
        user.setPhoneNum("110");
        user.setBirthday(new Date());
        user.setSal(2000.0);
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writevalueAsString(user);
        System.out.println(s);
    }
}
4.JSON字符串转换成Java对象
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class MyTest {
    public static void main(String[] args) throws IOException {
        String jsonStr = "{"username":"张三","password":"123456"}";
        //保证你提供的Java类的属性名和类型以及层级结构和json字符串一一对应即可。
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(jsonStr, User.class);
        System.out.println(user);
    }
}
5.复杂的JSON转换成Java对象

Car类

public class Car {
    private String carName;
    private Double carPrice;
    public String getCarName() {
        return carName;
    }
    public void setCarName(String carName) {
        this.carName = carName;
    }
    public Double getCarPrice() {
        return carPrice;
    }
    public void setCarPrice(Double carPrice) {
        this.carPrice = carPrice;
    }
    @Override
    public String toString() {
        return "Car{" +
                "carName='" + carName + ''' +
                ", carPrice=" + carPrice +
                '}';
    }
}

House类

public class House {
    private String houseName;
    private Double housePrice;
    public String getHouseName() {
        return houseName;
    }
    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }
    public Double getHousePrice() {
        return housePrice;
    }
    public void setHousePrice(Double housePrice) {
        this.housePrice = housePrice;
    }
    @Override
    public String toString() {
        return "House{" +
                "houseName='" + houseName + ''' +
                ", housePrice=" + housePrice +
                '}';
    }
}

Person类

import java.util.List;

public class Person {
    private String username;
    private Integer age;
    private Car car;
    private List girlfriend;
    private List house;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public List getGirlfriend() {
        return girlfriend;
    }
    public void setGirlfriend(List girlfriend) {
        this.girlfriend = girlfriend;
    }
    public List getHouse() {
        return house;
    }
    public void setHouse(List house) {
        this.house = house;
    }
    @Override
    public String toString() {
        return "Person{" +
                "username='" + username + ''' +
                ", age=" + age +
                ", car=" + car +
                ", girlfriend=" + girlfriend +
                ", house=" + house +
                '}';
    }
}

最终测试类MyTest

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
public class MyTest {
    public static void main(String[] args) throws IOException {
        //{"username":"王五","age":20,"car":{"carName":"宝马","carPrice":8888},"girlfriend":["刘亦菲","张曼玉"],"house":[{"houseName":"江滨花园",
        // "housePrice":50000},
        // {"houseName":"巴黎世家","housePrice":150000}]}
        String jsonStr = "{"username":"王五","age":20,"car":{"carName":"宝马","carPrice":8888},"girlfriend":["刘亦菲","张曼玉"]," +
                ""house":[{"houseName":"江滨花园","housePrice":50000},{"houseName":"巴黎世家","housePrice":150000}]}";
        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(jsonStr, Person.class);
        System.out.println(person);
    }
}
天气JSON转换Java对象
public class MyTest {
    public static void main(String[] args) {
        String jsonStr = "{"data":{"yesterday":{"date":"20日星期四","high":"高温 2℃","fx":"东南风","low":"低温 0℃"," +
                ""fl":"","type":"霾"},"city":"商洛","forecast":[{"date":"21日星期五","high":"高温 0℃"," +
                ""fengli":"","low":"低温 -1℃","fengxiang":"东南风","type":"小雪"},{"date":"22日星期六","high":"高温 2℃"," +
                ""fengli":"","low":"低温 -1℃","fengxiang":"东南风","type":"小雪"},{"date":"23日星期天","high":"高温 1℃"," +
                ""fengli":"","low":"低温 -2℃","fengxiang":"东南风","type":"小雪"},{"date":"24日星期一","high":"高温 1℃"," +
                ""fengli":"","low":"低温 -4℃","fengxiang":"西北风","type":"阴"},{"date":"25日星期二","high":"高温 1℃"," +
                ""fengli":"","low":"低温 -4℃","fengxiang":"北风","type":"阴"}]," +
                ""ganmao":"感冒多发期,适当减少外出频率,适量补充水分,适当增减衣物。","wendu":"-1"},"status":1000,"desc":"OK"}";
    }
}

总结:创建一个天气类,给IDEA中安装一个GsonFormat插件,就可以将复杂的JSON字符串转换成Java对象

之后在新建类的页面,鼠标右键单击打开Generate,进去之后找到GsonFormat选项,进去之后把需要转换的JSON字符串粘贴进去,会自动生成我们想要的Java对象
进去之后点击左下角setting按键,设置好所用的jar包


这样子就会将JSON字符串自动转换成一个Java对象了。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5713119.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存