前言:
下面打印日志用的是FastJSON依赖库中的 @Log4j2。依赖:
<!-- Alibaba Fastjson -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.80</version>
</dependency>
目录
普通字符串 -> json字符串
json字符串 -> 普通字符串
java对象 -> json字符串
json字符串 -> java对象
-
普通字符串 -> json字符串
代码:
public static void main(String[] args) {String s = "ningxingxing";String jsonS = "{\"name\":\""+s+"\"}";log.info("jsonS:{}",message);}
输出结果:
-
json字符串 -> 普通字符串
代码:
public static void main(String[] args) {// 定义一个字符串String s = "Hello NingXingxing!";// 转换为JSON格式的字符串String jsonString = "{\"message\":\""+s+"\"}";// 输出JSON格式的字符串log.info("jsonString:{}",jsonString);// 将JSON字符串解析为JSON对象JSONObject jsonObject = JSON.parseObject(jsonString);// 获取JSON对象中的属性值String message = jsonObject.getString("message");// 输出属性值log.info("message:{}",message);}
执行效果:
-
java对象 -> json字符串
java对象可以通过序列化转换为json字符串
代码:
package com.muyu.cloud.system.test;import com.alibaba.fastjson2.JSON;
import lombok.extern.log4j.Log4j2;/*** @author: 宁兴星* Date: 2024/9/13 20:50* Description:*/
class Person {private String name;private int age;// 构造函数public Person() {// 默认构造函数}// 带参数的构造函数public Person(String name, int age) {this.name = name;this.age = age;}// Getter 方法public String getName() {return name;}public int getAge() {return age;}// Setter 方法public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}
}@Log4j2
public class STest {public static void main(String[] args) {// 定义一个Person对象Person person = new Person();// 设置Person对象的属性值person.setName("NingXingxing");person.setAge(20);// 将Person对象转换为JSON格式的字符串String jsonString = JSON.toJSONString(person);// 输出JSON格式的字符串log.info("jsonString:{}",jsonString);}}
执行效果:
-
json字符串 -> java对象
代码:
package com.muyu.cloud.system.test;import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.log4j.Log4j2;/*** @author: 宁兴星* Date: 2024/9/13 20:50* Description:*/class Person {private String name;private int age;// 构造函数public Person() {// 默认构造函数}// 带参数的构造函数public Person(String name, int age) {this.name = name;this.age = age;}// Getter 方法public String getName() {return name;}public int getAge() {return age;}// Setter 方法public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}
}@Log4j2
public class STest {public static void main(String[] args) {// 定义一个JSON格式的字符串String jsonString = "{\"name\":\"NingXingxing\",\"age\":20}";// 将JSON格式的字符串解析为Person对象Person person = JSON.parseObject(jsonString, Person.class);// 输出Person对象的属性值log.info("name:{}, age:{}", person.getName(), person.getAge());}}
输出结果: