提交 dbe5d8df 编写于 作者: 小傅哥's avatar 小傅哥

小傅哥,feat:fastjson

上级
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
/.idea/
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.bugstack</groupId>
<artifactId>xfg-dev-tech-fastjson</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>xfg-dev-tech-app</module>
</modules>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.12</version>
<relativePath/>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.28</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>xfg-dev-tech</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 统一设定POM版本信息插件 -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.7</version>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cn.bugstack</groupId>
<artifactId>xfg-dev-tech-fastjson</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>xfg-dev-tech-app</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>xfg-dev-tech-app</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/**</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/**</include>
</includes>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.6</version>
<configuration>
<skipTests>true</skipTests>
<testFailureIgnore>false</testFailureIgnore>
<includes>
<include>**/*Test.java</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>cn.bugstack.xfg.dev.tech.Application</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package cn.bugstack.xfg.dev.tech;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 应用入口
* @create 2023-09-23 06:06
*/
@SpringBootApplication
@Configurable
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class);
}
}
server:
port: 8091
spring:
config:
name: xfg-dev-tech
package cn.bugstack.xfg.dev.tech.test;
import cn.bugstack.xfg.dev.tech.test.domain.model.entity.ChatCompletionRequest;
import cn.bugstack.xfg.dev.tech.test.domain.model.entity.UserEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.deserializer.ParseProcess;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.alibaba.fastjson2.JSONB;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import java.lang.reflect.Type;
import java.nio.file.attribute.UserPrincipal;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author Fuzhengwei bugstack.cn @小傅哥
* @description 单元测试 文档;<a href="https://alibaba.github.io/fastjson2/">fastjson2</a>
* @create 2023-09-23 06:18
*/
@Slf4j
public class ApiTest {
public static void main(String[] args) {
// 创建自定义的日期格式化器
SimpleDateFormatSerializer dateFormat = new SimpleDateFormatSerializer("dd/MM/yyyy");
// 创建Fastjson的配置对象
SerializeConfig config = new SerializeConfig();
config.put(Date.class, dateFormat);
// 将日期字符串转换为Java Date对象
String dateString = "Thu Sep 21 00:00:00 CST 2023";
Date date = JSON.parseObject(dateString, (Type) Date.class, (ParseProcess) config);
System.out.println(date);
String strJson = JSON.toJSONString(UserEntity.builder().build());
UserEntity userEntity = JSON.parseObject(strJson, UserEntity.class);
}
/**
* JsonProperty 设定序列化字段
*/
@Test
public void test_JsonProperty() {
ChatCompletionRequest request = ChatCompletionRequest.builder()
.model("3.5")
.topP(1.0D)
.maxTokens(1024)
.build();
log.info(JSON.toJSONString(request));
}
/**
* 1. 排除不被序列化的字段
* 2. 指定不被序列化的字段
* 3. 格式化序列化的字段
*/
@Test
public void test_excludes() {
UserEntity userEntity = UserEntity.builder()
.amount(100D)
.userName("xfg")
.password("abc000")
.createTime(new Date())
.build();
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
Collections.addAll(filter.getExcludes(), "password");
log.info(JSON.toJSONString(userEntity, filter));
}
@Test
public void test_parseObject() {
String jsonStr = "{\"userName\":\"xfg\",\"createTime\":\"21/09/2023\"}";
UserEntity userEntity = JSON.parseObject(jsonStr, UserEntity.class);
log.info(userEntity.toString());
}
@Test
public void test_map2json() {
Map<String, Object> map = new HashMap<>();
map.put("key1", "xfg");
map.put("key2", 123);
map.put("key3", false);
log.info(JSON.toJSONString(map));
}
@Test
public void test_json2map() {
String jsonString = "{\"key1\":\"xfg\",\"key2\":123,\"key3\":false}";
Map<String, Object> map = JSON.parseObject(jsonString, Map.class);
for (Map.Entry<String, Object> entry : map.entrySet()) {
log.info("{} : {}", entry.getKey(), entry.getValue());
}
}
@Test
public void test_JSONArray() {
String text1 = "{\"id\": 2,\"name\": \"fastjson2\"}";
JSONObject obj = JSON.parseObject(text1);
int id = obj.getIntValue("id");
String name = obj.getString("name");
String text2 = "[2, \"fastjson2\"]";
JSONArray array = JSON.parseArray(text2);
int id2 = array.getIntValue(0);
String name2 = array.getString(1);
}
@Test
public void test_toBytes() {
UserEntity userEntity = UserEntity.builder()
.amount(100D)
.userName("xfg")
.password("abc000")
.createTime(new Date())
.build();
byte[] bytes1 = JSONB.toBytes(userEntity);
byte[] bytes2 = JSONB.toBytes(userEntity, JSONWriter.Feature.BeanToArray);
}
/**
* toString 转对象
*/
@Test
public void testToString2Bean() throws Exception {
UserEntity userEntity = UserEntity.builder()
.amount(100D)
.userName("xfg")
.password("abc000")
.createTime(new Date())
.build();
log.info(userEntity.toString());
log.info(JSON.toJSONString(ToString2Bean.toObject(userEntity.toString(), UserEntity.class)));
}
}
package cn.bugstack.xfg.dev.tech.test;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ToString2Bean {
public static <T> T toObject(String str, Class<T> clazz) throws Exception {
// 创建一个新的对象
T obj = clazz.getDeclaredConstructor().newInstance();
// 获取类对象
Class<?> objClass = obj.getClass();
// 解析字符串
String[] fields = str.substring(str.indexOf("{") + 1, str.indexOf("}")).split(", ");
// 遍历成员变量
for (String field : fields) {
// 获取成员变量名和值
String[] parts = field.split("=");
// 获取成员变量对象
Field objField = objClass.getDeclaredField(parts[0].trim());
// 设置成员变量可以访问
objField.setAccessible(true);
// 设置成员变量的值
objField.set(obj, convertValue(objField.getType(), parts[1].trim()));
// 设置成员变量不可访问
objField.setAccessible(false);
}
return obj;
}
public static Object convertValue(Class<?> type, String value) throws ParseException {
if ("'null'".equals(value) || "null".equals(value)) return null;
if (type == int.class || type == Integer.class) {
return Integer.parseInt(value);
} else if (type == long.class || type == Long.class) {
return Long.parseLong(value);
} else if (type == float.class || type == Float.class) {
return Float.parseFloat(value);
} else if (type == double.class || type == Double.class) {
return Double.parseDouble(value);
} else if (type == boolean.class || type == Boolean.class) {
return Boolean.parseBoolean(value);
} else if (type == char.class || type == Character.class) {
return value.charAt(0);
} else if (type == byte.class || type == Byte.class) {
return Byte.parseByte(value);
} else if (type == short.class || type == Short.class) {
return Short.parseShort(value);
} else if (type == Date.class) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.parse(value);
} else {
return value;
}
}
}
package cn.bugstack.xfg.dev.tech.test.domain.model.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatCompletionRequest {
private String model;
@JsonProperty("top_p")
private Double topP = 1d;
@JsonProperty("max_tokens")
private Integer maxTokens = 2048;
}
package cn.bugstack.xfg.dev.tech.test.domain.model.entity;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.text.SimpleDateFormat;
import java.util.Date;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {
private String userName;
private String password;
// 不被序列化
@JSONField(name="amount", serialize=false)
private Double amount;
// 序列化格式
@JSONField(name="createTime", format="dd/MM/yyyy", ordinal = 3)
private Date createTime;
@Override
public String toString() {
return "UserEntity{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
", amount=" + amount +
", createTime=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTime) +
'}';
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册