首页 > 编程语言 >JSON数据和Java对象的相互转换

JSON数据和Java对象的相互转换

时间:2022-08-21 11:46:34浏览次数:67  
标签:转换 name gender age Person JSON new Java public

JSON数据和Java对象的相互转换

  • JSON解析器
    • 创建的解析器:Jsonlib,Gson,Fastjson,jackson

JSON转为Java对象

  • 使用步骤:
    • 导入jackson相关的jar包
    • 创建Jackson革新对象 ObjectMapper
    • 调用ObjectMapper的相关方法进行转换
      • readValue(json字符串,Class)
    @Test
    public void Test05() throws Exception {
        String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":19}";
        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.readValue(json, Person.class);
        System.out.println(person);//Person{name='张三', age=19, gender='男', date=null}
    }

Java对象转换JSON

  • 使用步骤:
    • 导入jackson相关的jar包
    • 创建Jackson革新对象 ObjectMapper
    • 调用ObjectMapper的相关方法进行转换
package com.ailyt;

import com.ailyt.domain.Person;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.FileWriter;

public class JacksonTest {
    //Java对象转为Json字符串
    @Test
    public void Test01() throws Exception {
        //创建Person对象
        Person person = new Person();
        person.setName("张三");
        person.setAge(17);
        person.setGender("男");

        //创建Jackson的核心对象ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        //转换
        /**
         * 转换方法:
         *  writerValue(参数1,obj)
         *      参数1:
         *          File:将obj对象转换为json字符串,并保存到指定的文件中
         *          Writer:将obj对象转换为json字符串,并将json数据填充到字符输出流中
         *          OutputStream:将obj对象转换为json字符串,并将json数据填充到字节输出流中
         *  writerValueAsString(obj):将对象转为json字符串
         */
        String json = mapper.writeValueAsString(person);
        System.out.println(json);//{"name":"张三","age":17,"gender":"男"}

        //writeValue 将文件写入到D:\\a.txt
        FileWriter fileWriter = new FileWriter("D:\\a.txt");
        mapper.writeValue(fileWriter,person);
        fileWriter.close();
    }
}

  • 注解:
    • @JsonIgnore:排除属性
    • @JsonFormat:属性值得格式化
package com.ailyt.domain;

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

import java.util.Date;

public class Person {
    private String name;
    private int age;
    private String gender;
    //@JsonIgnore//忽略改属性
    @JsonFormat(pattern = "yyyy-MM-dd")//
    private Date date;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", date=" + date +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getDate() {
        return date;
    }

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

    public Person() {
    }

    public Person(String name, int age, String gender, Date date) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.date = date;
    }
}

    @Test
    public void Test02() throws Exception {
        //创建Person对象
        Person person = new Person();
        person.setName("张三");
        person.setAge(17);
        person.setGender("男");
        person.setDate(new Date());

        ObjectMapper mapper = new ObjectMapper();
        String value = mapper.writeValueAsString(person);
        System.out.println(value);//{"name":"张三","age":17,"gender":"男","date":1661051661487}
    }

复杂Java对象转换

  • List:数组
  • Map:对象格式一直
    @Test
    public void Test03() throws Exception {
        //创建Person对象
        Person person1 = new Person();
        person1.setName("张三");
        person1.setAge(17);
        person1.setGender("男");
        person1.setDate(new Date());

        Person person2 = new Person();
        person2.setName("李四");
        person2.setAge(15);
        person2.setGender("女");
        person2.setDate(new Date());

        Person person3 = new Person();
        person3.setName("王五");
        person3.setAge(21);
        person3.setGender("男");
        person3.setDate(new Date());

        ArrayList<Person> people = new ArrayList<>();

        Collections.addAll(people,person1,person2,person3);

        ObjectMapper mapper = new ObjectMapper();

        String s = mapper.writeValueAsString(people);
        System.out.println(s);//[{"name":"张三","age":17,"gender":"男","date":"2022-08-21"},{"name":"李四","age":15,"gender":"女","date":"2022-08-21"},{"name":"王五","age":21,"gender":"男","date":"2022-08-21"}]

    }


    @Test
    public void Test04() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age",19);
        map.put("gender",'男');

        ObjectMapper mapper = new ObjectMapper();

        String s = mapper.writeValueAsString(map);
        System.out.println(s);//{"gender":"男","name":"张三","age":19}
    }

标签:转换,name,gender,age,Person,JSON,new,Java,public
From: https://www.cnblogs.com/ailhy/p/16609663.html

相关文章

  • Java后端开发需要学什么?
    Java基础Java是一门纯粹的面向对象的编程语言,所以除了基础语法之外,必须得弄懂它的oop特性:封装、继承、多态。此外还有泛型、反射的特性,很多框架的技术都依赖它,比如S......
  • json转java对象以及校验用户名是否存在案例
    json转java对象使用步骤:1、导入jackson的相关jar包2、创建Jackson核心对象ObjectMapper3、调用ObjectMapper的相关方法进行转换1、readValue(js......
  • python输入和类型转换
    输入获取用户使用键盘录入的内容使用的函数是input()变量=input(‘提示的信息’)1.代码从上到下执行,遇到input函数之后 类型转换根据代码的需要,将一种数据类型......
  • Java SE 14 新增特性
    JavaSE14新增特性作者:Grey原文地址:JavaSE14新增特性源码源仓库:Github:java_new_features镜像仓库:GitCode:java_new_featuresswitch增强switch表达式在Ja......
  • JSON_语法_值得获取
    JSON_语法_值得获取json对象.键名json对象["键名"]数据对象[索引]获取值:<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</......
  • JSON_概念和JSON_语法_定义
    JSON:概念:JavaScriptObjectNotationJavaScript对象表示法Personperson=newPerson();person.setName("张三");person.setAge(23);person.setGender("男");v......
  • JSON解析器的Jackson_java对象转json_List&Map和JSON解析器的Jackson_json转Java对象
    JSON解析器的Jackson_java对象转json_List&Map复杂java对象转换1.list:数组@Testpublicvoidtest3()throwsException{//创建Person对象......
  • Java概述
    从项目到代码找工作前的整个学习体系(学会这些东西去解决问题,不单单去学这些东西)JavaSE知识图Java语言跨平台原理Java语言特点完全面向对象:Java支持封装,继承,多态,面......
  • JSON解析器Jackson_java对象转json和JSON解析器Jackson_java对象转json注解
    JSON解析器Jackson_java对象转jsonJSON数据和Java对象的相互转换JSON解析器:常见的解析器:Jsonlib,Gson,fastjson,jackson1.JSON转为Java对象在后......
  • java对象转json
    java对象转jsonjson解析器:常见的解析器:Jsonlib,Gson,fastjson,jackson使用步骤:1、导入jackson的相关jar包2、创建Jackson核心对象ObjectMapper3、调用......