Java中JSON字符串和Java对象的互转

2年前 (2022) 程序员胖胖胖虎阿
361 0 0

1.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","*");

2.JSON字符串转换Java对象(使用截取字符串的方法)

测试类:

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 + '\'' +
                '}';
    }
}

3.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<String> 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<User> 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<String, User> 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);


    }
}

User类和Car类

public class User {
    private String username;
    private String password;
    private int age;
    private String phoneNum;
    private Car car;
    private List<String> 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<String> girlfriend) {
        this.username = username;
        this.password = password;
        this.age = age;
        this.phoneNum = phoneNum;
        this.car = car;
        this.girlfriend = girlfriend;
    }

    public List<String> getGirlfriend() {
        return girlfriend;
    }

    public void setGirlfriend(List<String> 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;
    }
}
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 +
                '}';
    }
}

4.注解的作用

测试类:

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);
    }
}

User类:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

public class User {
    @JsonProperty("name") //指定json字符中键的名称
    private String username;
    @JsonIgnore//排除某个属性不要转换成JSON,给类的属性上加上这个注解。
    private String password;
    private int age;
    //@JsonIgnore
    private String phoneNum;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date birthday;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Double sal;

    public Double getSal() {
        return sal;
    }

    public void setSal(Double sal) {
        this.sal = sal;
    }

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    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;
    }
}

5.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);

    }
}

User类:

public class User {
    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 "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

6.复杂的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<String> girlfriend;
    private List<House> 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<String> getGirlfriend() {
        return girlfriend;
    }

    public void setGirlfriend(List<String> girlfriend) {
        this.girlfriend = girlfriend;
    }

    public List<House> getHouse() {
        return house;
    }

    public void setHouse(List<House> house) {
        this.house = house;
    }

    @Override
    public String toString() {
        return "Person{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", car=" + car +
                ", girlfriend=" + girlfriend +
                ", house=" + house +
                '}';
    }
}

测试类:

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);


    }
}

7.天气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 = "{\"data\":{\"yesterday\":{\"date\":\"20日星期四\",\"high\":\"高温 2℃\",\"fx\":\"东南风\",\"low\":\"低温 0℃\"," +
                "\"fl\":\"<![CDATA[2级]]>\",\"type\":\"霾\"},\"city\":\"商洛\",\"forecast\":[{\"date\":\"21日星期五\",\"high\":\"高温 0℃\"," +
                "\"fengli\":\"<![CDATA[2级]]>\",\"low\":\"低温 -1℃\",\"fengxiang\":\"东南风\",\"type\":\"小雪\"},{\"date\":\"22日星期六\",\"high\":\"高温 2℃\"," +
                "\"fengli\":\"<![CDATA[1级]]>\",\"low\":\"低温 -1℃\",\"fengxiang\":\"东南风\",\"type\":\"小雪\"},{\"date\":\"23日星期天\",\"high\":\"高温 1℃\"," +
                "\"fengli\":\"<![CDATA[1级]]>\",\"low\":\"低温 -2℃\",\"fengxiang\":\"东南风\",\"type\":\"小雪\"},{\"date\":\"24日星期一\",\"high\":\"高温 1℃\"," +
                "\"fengli\":\"<![CDATA[1级]]>\",\"low\":\"低温 -4℃\",\"fengxiang\":\"西北风\",\"type\":\"阴\"},{\"date\":\"25日星期二\",\"high\":\"高温 1℃\"," +
                "\"fengli\":\"<![CDATA[1级]]>\",\"low\":\"低温 -4℃\",\"fengxiang\":\"北风\",\"type\":\"阴\"}]," +
                "\"ganmao\":\"感冒多发期,适当减少外出频率,适量补充水分,适当增减衣物。\",\"wendu\":\"-1\"},\"status\":1000,\"desc\":\"OK\"}";

        ObjectMapper mapper = new ObjectMapper();
        TianQi tianQi = mapper.readValue(jsonStr, TianQi.class);
        String date = tianQi.getData().getYesterday().getDate();
        System.out.println(date);

    }
}

TianQi类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class TianQi {


    /**
     * data : {"yesterday":{"date":"20日星期四","high":"高温 2℃","fx":"东南风","low":"低温 0℃","fl":"<![CDATA[2级]]>","type":"霾"},"city":"商洛","forecast":[{
     * "date":"21日星期五","high":"高温 0℃","fengli":"<![CDATA[2级]]>","low":"低温 -1℃","fengxiang":"东南风","type":"小雪"},{"date":"22日星期六","high":"高温 2℃",
     * "fengli":"<![CDATA[1级]]>","low":"低温 -1℃","fengxiang":"东南风","type":"小雪"},{"date":"23日星期天","high":"高温 1℃","fengli":"<![CDATA[1级]]>","low":"低温
     * -2℃","fengxiang":"东南风","type":"小雪"},{"date":"24日星期一","high":"高温 1℃","fengli":"<![CDATA[1级]]>","low":"低温 -4℃","fengxiang":"西北风","type":"阴"},{
     * "date":"25日星期二","high":"高温 1℃","fengli":"<![CDATA[1级]]>","low":"低温 -4℃","fengxiang":"北风","type":"阴"}],"ganmao
     * ":"感冒多发期,适当减少外出频率,适量补充水分,适当增减衣物。","wendu":"-1"}
     * status : 1000
     * desc : OK
     */

    private DataBean data;
    private int status;
    private String desc;

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class DataBean {
        /**
         * yesterday : {"date":"20日星期四","high":"高温 2℃","fx":"东南风","low":"低温 0℃","fl":"<![CDATA[2级]]>","type":"霾"}
         * city : 商洛
         * forecast : [{"date":"21日星期五","high":"高温 0℃","fengli":"<![CDATA[2级]]>","low":"低温 -1℃","fengxiang":"东南风","type":"小雪"},{"date":"22日星期六",
         * "high":"高温 2℃","fengli":"<![CDATA[1级]]>","low":"低温 -1℃","fengxiang":"东南风","type":"小雪"},{"date":"23日星期天","high":"高温 1℃",
         * "fengli":"<![CDATA[1级]]>","low":"低温 -2℃","fengxiang":"东南风","type":"小雪"},{"date":"24日星期一","high":"高温 1℃","fengli":"<![CDATA[1级]]>",
         * "low":"低温 -4℃","fengxiang":"西北风","type":"阴"},{"date":"25日星期二","high":"高温 1℃","fengli":"<![CDATA[1级]]>","low":"低温 -4℃","fengxiang":"北风",
         * "type":"阴"}]
         * ganmao : 感冒多发期,适当减少外出频率,适量补充水分,适当增减衣物。
         * wendu : -1
         */

        private YesterdayBean yesterday;
        private String city;
        private String ganmao;
        private String wendu;
        private List<ForecastBean> forecast;

        public YesterdayBean getYesterday() {
            return yesterday;
        }

        public void setYesterday(YesterdayBean yesterday) {
            this.yesterday = yesterday;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getGanmao() {
            return ganmao;
        }

        public void setGanmao(String ganmao) {
            this.ganmao = ganmao;
        }

        public String getWendu() {
            return wendu;
        }

        public void setWendu(String wendu) {
            this.wendu = wendu;
        }

        public List<ForecastBean> getForecast() {
            return forecast;
        }

        public void setForecast(List<ForecastBean> forecast) {
            this.forecast = forecast;
        }

        @JsonIgnoreProperties(ignoreUnknown = true)
        public static class YesterdayBean {
            /**
             * date : 20日星期四
             * high : 高温 2℃
             * fx : 东南风
             * low : 低温 0℃
             * fl : <![CDATA[2级]]>
             * type : 霾
             */

            private String date;
            private String high;
            private String fx;
            private String low;
            private String fl;
            private String type;

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getHigh() {
                return high;
            }

            public void setHigh(String high) {
                this.high = high;
            }

            public String getFx() {
                return fx;
            }

            public void setFx(String fx) {
                this.fx = fx;
            }

            public String getLow() {
                return low;
            }

            public void setLow(String low) {
                this.low = low;
            }

            public String getFl() {
                return fl;
            }

            public void setFl(String fl) {
                this.fl = fl;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }
        }

        @JsonIgnoreProperties(ignoreUnknown = true)
        public static class ForecastBean {
            /**
             * date : 21日星期五
             * high : 高温 0℃
             * fengli : <![CDATA[2级]]>
             * low : 低温 -1℃
             * fengxiang : 东南风
             * type : 小雪
             */

            private String date;
            private String high;
            private String fengli;
            private String low;
            private String fengxiang;
            private String type;

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getHigh() {
                return high;
            }

            public void setHigh(String high) {
                this.high = high;
            }

            public String getFengli() {
                return fengli;
            }

            public void setFengli(String fengli) {
                this.fengli = fengli;
            }

            public String getLow() {
                return low;
            }

            public void setLow(String low) {
                this.low = low;
            }

            public String getFengxiang() {
                return fengxiang;
            }

            public void setFengxiang(String fengxiang) {
                this.fengxiang = fengxiang;
            }

            public String getType() {
                return type;
            }

            public void setType(String type) {
                this.type = type;
            }
        }
    }
}

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

Java中JSON字符串和Java对象的互转

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

Java中JSON字符串和Java对象的互转

 Java中JSON字符串和Java对象的互转

最后就会将JSON字符串自动转换成一个Java对象了。

版权声明:程序员胖胖胖虎阿 发表于 2022年9月25日 下午11:08。
转载请注明:Java中JSON字符串和Java对象的互转 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...