diff --git a/tml-sdk-java-core/pom.xml b/tml-sdk-java-core/pom.xml index baa4ffe..3fc8970 100644 --- a/tml-sdk-java-core/pom.xml +++ b/tml-sdk-java-core/pom.xml @@ -33,6 +33,18 @@ 5.8.2 test + + + com.squareup.okhttp3 + okhttp + 4.12.0 + + + + com.alibaba.fastjson2 + fastjson2 + 2.0.43 + diff --git a/tml-sdk-java-core/src/main/java/io/github/timemachinelab/util/HttpUtils.java b/tml-sdk-java-core/src/main/java/io/github/timemachinelab/util/HttpUtils.java new file mode 100644 index 0000000..250dfa5 --- /dev/null +++ b/tml-sdk-java-core/src/main/java/io/github/timemachinelab/util/HttpUtils.java @@ -0,0 +1,563 @@ +package io.github.timemachinelab.util; + +import okhttp3.*; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * HTTP工具类,基于OkHttp封装 + * + *

+ * 提供HTTP请求的发送功能,支持GET、POST、PUT、DELETE等常用方法, + * 同时支持代理配置和自定义请求头。 + *

+ * + *
+ * // 简单GET请求
+ * String response = HttpUtils.get("https://api.example.com/data");
+ * 
+ * // 带代理的POST请求
+ * HttpUtils.setProxyConfig(new HttpUtils.ProxyConfig("127.0.0.1", 8080));
+ * String response = HttpUtils.post("https://api.example.com/create", jsonBody);
+ * 
+ * // 清除代理配置
+ * HttpUtils.clearProxyConfig();
+ * 
+ * + * @author TimeMachineLab + * @since 1.0 + */ +public class HttpUtils { + + private static final int DEFAULT_TIMEOUT = 60; + private static final String DEFAULT_CHARSET = "UTF-8"; + + // 默认客户端和代理客户端 + private static final OkHttpClient DEFAULT_CLIENT; + private static volatile OkHttpClient PROXY_CLIENT; + + // 代理配置 + private static volatile ProxyConfig proxyConfig; + + static { + DEFAULT_CLIENT = new OkHttpClient.Builder() + .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) + .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) + .followRedirects(true) + .build(); + } + + /** + * 代理配置类 + * + *

+ * 用于配置HTTP代理服务器信息,支持基本认证。 + *

+ * + *
+     * // 简单代理配置
+     * ProxyConfig config = new ProxyConfig("127.0.0.1", 8080);
+     * 
+     * // 带认证的代理配置
+     * ProxyConfig config = new ProxyConfig("127.0.0.1", 8080, "username", "password");
+     * 
+ * + * @since 1.0 + */ + public static class ProxyConfig { + private final String host; + private final int port; + private final String username; + private final String password; + private final Proxy.Type type; + + /** + * 创建简单代理配置(无认证) + * + * @param host 代理服务器主机 + * @param port 代理服务器端口 + */ + public ProxyConfig(String host, int port) { + this(host, port, null, null, Proxy.Type.HTTP); + } + + /** + * 创建带认证的代理配置 + * + * @param host 代理服务器主机 + * @param port 代理服务器端口 + * @param username 代理用户名 + * @param password 代理密码 + */ + public ProxyConfig(String host, int port, String username, String password) { + this(host, port, username, password, Proxy.Type.HTTP); + } + + /** + * 创建完整的代理配置 + * + * @param host 代理服务器主机 + * @param port 代理服务器端口 + * @param username 代理用户名 + * @param password 代理密码 + * @param type 代理类型 + */ + public ProxyConfig(String host, int port, String username, String password, Proxy.Type type) { + this.host = host; + this.port = port; + this.username = username; + this.password = password; + this.type = type; + } + + /** + * 获取代理服务器主机 + * + * @return 代理服务器主机 + */ + public String getHost() { + return host; + } + + /** + * 获取代理服务器端口 + * + * @return 代理服务器端口 + */ + public int getPort() { + return port; + } + + /** + * 获取代理用户名 + * + * @return 代理用户名 + */ + public String getUsername() { + return username; + } + + /** + * 获取代理密码 + * + * @return 代理密码 + */ + public String getPassword() { + return password; + } + + /** + * 获取代理类型 + * + * @return 代理类型 + */ + public Proxy.Type getType() { + return type; + } + + /** + * 检查是否需要认证 + * + * @return 如果需要认证返回true + */ + public boolean hasAuth() { + return username != null && !username.isEmpty() && password != null; + } + } + + /** + * 设置代理配置 + * + *

+ * 设置全局代理配置,之后的所有HTTP请求都会通过代理服务器发送。 + *

+ * + *
+     * HttpUtils.setProxyConfig(new HttpUtils.ProxyConfig("127.0.0.1", 8080));
+     * 
+ * + * @param config 代理配置,为null时清除代理配置 + */ + public static void setProxyConfig(ProxyConfig config) { + proxyConfig = config; + if (config != null) { + PROXY_CLIENT = createProxyClient(config); + } else { + PROXY_CLIENT = null; + } + } + + /** + * 清除代理配置 + * + *

+ * 清除当前设置的代理配置,之后的HTTP请求将直接发送。 + *

+ * + *
+     * HttpUtils.clearProxyConfig();
+     * 
+ */ + public static void clearProxyConfig() { + proxyConfig = null; + PROXY_CLIENT = null; + } + + /** + * 获取当前代理配置 + * + * @return 当前代理配置,如果没有设置返回null + */ + public static ProxyConfig getProxyConfig() { + return proxyConfig; + } + + /** + * 创建代理客户端 + * + *

+ * 根据代理配置创建OkHttpClient实例。 + *

+ * + * @param config 代理配置 + * @return 配置了代理的OkHttpClient + */ + private static OkHttpClient createProxyClient(ProxyConfig config) { + Proxy proxy = new Proxy(config.getType(), new InetSocketAddress(config.getHost(), config.getPort())); + + OkHttpClient.Builder builder = new OkHttpClient.Builder() + .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) + .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) + .followRedirects(true) + .proxy(proxy); + + // 如果代理需要认证 + if (config.hasAuth()) { + builder.proxyAuthenticator((route, response) -> { + String credential = Credentials.basic(config.getUsername(), config.getPassword()); + return response.request().newBuilder() + .header("Proxy-Authorization", credential) + .build(); + }); + } + + return builder.build(); + } + + /** + * 获取当前使用的客户端 + * + *

+ * 根据是否配置了代理返回相应的OkHttpClient。 + *

+ * + * @return 当前使用的OkHttpClient + */ + private static OkHttpClient getCurrentClient() { + return PROXY_CLIENT != null ? PROXY_CLIENT : DEFAULT_CLIENT; + } + + /** + * 发送GET请求 + * + *

+ * 发送简单的GET请求到指定URL。 + *

+ * + *
+     * String response = HttpUtils.get("https://api.example.com/data");
+     * 
+ * + * @param url 请求URL + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String get(String url) throws IOException { + return get(url, null); + } + + /** + * 发送GET请求 + * + *

+ * 发送带自定义请求头的GET请求。 + *

+ * + *
+     * Map headers = new HashMap<>();
+     * headers.put("Authorization", "Bearer token123");
+     * String response = HttpUtils.get("https://api.example.com/data", headers);
+     * 
+ * + * @param url 请求URL + * @param headers 请求头 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String get(String url, Map headers) throws IOException { + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .get(); + + if (headers != null) { + headers.forEach(requestBuilder::header); + } + + Request request = requestBuilder.build(); + try (Response response = getCurrentClient().newCall(request).execute()) { + if (response.isSuccessful()) { + return response.body() != null ? response.body().string() : ""; + } else { + throw new IOException("HTTP请求失败,状态码: " + response.code()); + } + } + } + + /** + * 发送POST请求 + * + *

+ * 发送JSON格式的POST请求。 + *

+ * + *
+     * String jsonBody = "{\"name\":\"test\",\"age\":20}";
+     * String response = HttpUtils.post("https://api.example.com/create", jsonBody);
+     * 
+ * + * @param url 请求URL + * @param body 请求体 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String post(String url, String body) throws IOException { + return post(url, body, "application/json", null); + } + + /** + * 发送POST请求 + * + *

+ * 发送指定内容类型的POST请求。 + *

+ * + *
+     * String xmlBody = "test";
+     * String response = HttpUtils.post("https://api.example.com/create", xmlBody, "application/xml");
+     * 
+ * + * @param url 请求URL + * @param body 请求体 + * @param contentType 内容类型 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String post(String url, String body, String contentType) throws IOException { + return post(url, body, contentType, null); + } + + /** + * 发送POST请求 + * + *

+ * 发送完整的POST请求,支持自定义内容类型和请求头。 + *

+ * + *
+     * Map headers = new HashMap<>();
+     * headers.put("Authorization", "Bearer token123");
+     * headers.put("X-Custom-Header", "value");
+     * String response = HttpUtils.post("https://api.example.com/create", jsonBody, "application/json", headers);
+     * 
+ * + * @param url 请求URL + * @param body 请求体 + * @param contentType 内容类型 + * @param headers 请求头 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String post(String url, String body, String contentType, Map headers) + throws IOException { + RequestBody requestBody = body != null + ? RequestBody.create(body, MediaType.parse(contentType != null ? contentType : "application/json")) + : RequestBody.create("", MediaType.parse("application/json")); + + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .post(requestBody); + + if (contentType != null) { + requestBuilder.header("Content-Type", contentType); + } + + if (headers != null) { + headers.forEach(requestBuilder::header); + } + + Request request = requestBuilder.build(); + try (Response response = getCurrentClient().newCall(request).execute()) { + if (response.isSuccessful()) { + return response.body() != null ? response.body().string() : ""; + } else { + throw new IOException("HTTP请求失败,状态码: " + response.code()); + } + } + } + + /** + * 发送PUT请求 + * + *

+ * 发送JSON格式的PUT请求。 + *

+ * + *
+     * String jsonBody = "{\"name\":\"updated\"}";
+     * String response = HttpUtils.put("https://api.example.com/update/1", jsonBody);
+     * 
+ * + * @param url 请求URL + * @param body 请求体 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String put(String url, String body) throws IOException { + return put(url, body, "application/json", null); + } + + /** + * 发送PUT请求 + * + *

+ * 发送完整的PUT请求,支持自定义内容类型和请求头。 + *

+ * + *
+     * Map headers = new HashMap<>();
+     * headers.put("Authorization", "Bearer token123");
+     * String response = HttpUtils.put("https://api.example.com/update/1", jsonBody, "application/json", headers);
+     * 
+ * + * @param url 请求URL + * @param body 请求体 + * @param contentType 内容类型 + * @param headers 请求头 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String put(String url, String body, String contentType, Map headers) + throws IOException { + RequestBody requestBody = body != null + ? RequestBody.create(body, MediaType.parse(contentType != null ? contentType : "application/json")) + : RequestBody.create("", MediaType.parse("application/json")); + + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .put(requestBody); + + if (contentType != null) { + requestBuilder.header("Content-Type", contentType); + } + + if (headers != null) { + headers.forEach(requestBuilder::header); + } + + Request request = requestBuilder.build(); + try (Response response = getCurrentClient().newCall(request).execute()) { + if (response.isSuccessful()) { + return response.body() != null ? response.body().string() : ""; + } else { + throw new IOException("HTTP请求失败,状态码: " + response.code()); + } + } + } + + /** + * 发送DELETE请求 + * + *

+ * 发送简单的DELETE请求。 + *

+ * + *
+     * String response = HttpUtils.delete("https://api.example.com/delete/1");
+     * 
+ * + * @param url 请求URL + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String delete(String url) throws IOException { + return delete(url, null); + } + + /** + * 发送DELETE请求 + * + *

+ * 发送带自定义请求头的DELETE请求。 + *

+ * + *
+     * Map headers = new HashMap<>();
+     * headers.put("Authorization", "Bearer token123");
+     * String response = HttpUtils.delete("https://api.example.com/delete/1", headers);
+     * 
+ * + * @param url 请求URL + * @param headers 请求头 + * @return 响应内容 + * @throws IOException 如果请求失败 + */ + public static String delete(String url, Map headers) throws IOException { + Request.Builder requestBuilder = new Request.Builder() + .url(url) + .delete(); + + if (headers != null) { + headers.forEach(requestBuilder::header); + } + + Request request = requestBuilder.build(); + try (Response response = getCurrentClient().newCall(request).execute()) { + if (response.isSuccessful()) { + return response.body() != null ? response.body().string() : ""; + } else { + throw new IOException("HTTP请求失败,状态码: " + response.code()); + } + } + } + + /** + * 获取默认的OkHttpClient实例 + * + *

+ * 获取默认的OkHttpClient实例,用于自定义请求。 + *

+ * + * @return OkHttpClient实例 + */ + public static OkHttpClient getDefaultClient() { + return DEFAULT_CLIENT; + } + + /** + * 创建新的OkHttpClient构建器 + * + *

+ * 创建新的OkHttpClient构建器,用于自定义客户端配置。 + *

+ * + * @return OkHttpClient.Builder实例 + */ + public static OkHttpClient.Builder newClientBuilder() { + return new OkHttpClient.Builder(); + } +} \ No newline at end of file diff --git a/tml-sdk-java-core/src/main/java/io/github/timemachinelab/util/JsonUtil.java b/tml-sdk-java-core/src/main/java/io/github/timemachinelab/util/JsonUtil.java new file mode 100644 index 0000000..7d7e94e --- /dev/null +++ b/tml-sdk-java-core/src/main/java/io/github/timemachinelab/util/JsonUtil.java @@ -0,0 +1,74 @@ +package io.github.timemachinelab.util; + +import com.alibaba.fastjson2.JSON; + +/** + * JSON工具类,基于fastjson2封装 + * + *

+ * 提供对象与JSON字符串之间的相互转换功能 + *

+ * + *
+ * JsonUtil.toJson(null)         = "null"
+ * JsonUtil.toJson(new User())   = "{\"name\":\"test\",\"age\":20}"
+ * JsonUtil.fromJson("{\"name\":\"test\"}", User.class) = User对象
+ * 
+ * + * @author TimeMachineLab + * @since 1.0 + */ +public class JsonUtil { + + /** + *

+ * 将对象转换为JSON字符串 + *

+ * + *

+ * 支持Java对象、集合、数组等各种类型的序列化 + *

+ * + *
+     * JsonUtil.toJson(null)         = "null"
+     * JsonUtil.toJson("")            = "\"\""
+     * JsonUtil.toJson("abc")         = "\"abc\""
+     * JsonUtil.toJson(new int[]{1,2,3}) = "[1,2,3]"
+     * JsonUtil.toJson(new User("test", 20)) = "{\"name\":\"test\",\"age\":20}"
+     * 
+ * + * @param object 要转换的对象,可以为null + * @return JSON字符串,如果对象为null返回"null" + * @since 1.0 + */ + public static String toJson(Object object) { + return JSON.toJSONString(object); + } + + /** + *

+ * 将JSON字符串转换为指定类型的对象 + *

+ * + *

+ * 支持Java对象、集合、数组等各种类型的反序列化 + *

+ * + *
+     * JsonUtil.fromJson("null", String.class)              = null
+     * JsonUtil.fromJson("\"abc\"", String.class)           = "abc"
+     * JsonUtil.fromJson("[1,2,3]", int[].class)           = [1,2,3]
+     * JsonUtil.fromJson("{\"name\":\"test\"}", User.class) = User对象
+     * 
+ * + * @param json JSON字符串,可以为null + * @param clazz 目标类型,不能为null + * @param 目标类型 + * @return 转换后的对象,如果JSON为null或"null"返回null + * @throws com.alibaba.fastjson2.JSONException 如果JSON格式错误或无法转换 + * @since 1.0 + */ + public static T fromJson(String json, Class clazz) { + return JSON.parseObject(json, clazz); + } +} \ No newline at end of file diff --git a/tml-sdk-java-core/src/readme/HttpUtils.md b/tml-sdk-java-core/src/readme/HttpUtils.md new file mode 100644 index 0000000..c88d7e7 --- /dev/null +++ b/tml-sdk-java-core/src/readme/HttpUtils.md @@ -0,0 +1,167 @@ +# HttpUtils HTTP工具类使用说明 + +## 概述 + +`HttpUtils` 是一个基于OkHttp封装的HTTP工具类,提供同步的HTTP请求发送功能。该工具类支持GET、POST、PUT、DELETE等常用HTTP方法,同时提供代理配置和自定义请求头功能。 + +## 特性 + +- ✅ **同步调用**:所有方法都是同步的,使用简单直观 +- ✅ **多方法支持**:支持GET、POST、PUT、DELETE等HTTP方法 +- ✅ **代理支持**:内置代理配置功能,支持HTTP代理 +- ✅ **超时配置**:默认60秒超时,可自定义配置 +- ✅ **重定向支持**:自动处理HTTP重定向 +- ✅ **异常处理**:完善的异常处理机制 +- ✅ **高性能**:基于OkHttp,性能优异 + +## 快速开始 + +### 基本用法 + +```java +import io.github.timemachinelab.util.HttpUtils; + +// 简单GET请求 +String response = HttpUtils.get("https://api.example.com/data"); +System.out.println("响应内容: " + response); + +// POST请求发送JSON数据 +String jsonBody = "{\"name\":\"张三\",\"age\":25}"; +String postResponse = HttpUtils.post("https://api.example.com/users", jsonBody); +System.out.println("POST响应: " + postResponse); +``` + +### 使用代理 + +```java +// 配置代理 +HttpUtils.setProxyConfig(new HttpUtils.ProxyConfig("127.0.0.1", 8080)); + +// 发送带代理的请求 +String response = HttpUtils.get("https://api.example.com/data"); + +// 清除代理配置 +HttpUtils.clearProxyConfig(); +``` + +### 自定义请求头 + +```java +// 创建自定义请求头 +Map headers = new HashMap<>(); +headers.put("Authorization", "Bearer your-token"); +headers.put("Content-Type", "application/json"); + +// 发送带自定义头的请求 +String response = HttpUtils.get("https://api.example.com/protected", headers); +``` + +## API列表 + +| 方法签名 | 描述 | 返回值 | +|---------|------|--------| +| `get(String url)` | 发送GET请求 | `String` | +| `get(String url, Map headers)` | 发送带自定义头的GET请求 | `String` | +| `post(String url, String body)` | 发送POST请求 | `String` | +| `post(String url, String body, Map headers)` | 发送带自定义头的POST请求 | `String` | +| `put(String url, String body)` | 发送PUT请求 | `String` | +| `put(String url, String body, Map headers)` | 发送带自定义头的PUT请求 | `String` | +| `delete(String url)` | 发送DELETE请求 | `String` | +| `delete(String url, Map headers)` | 发送带自定义头的DELETE请求 | `String` | +| `setProxyConfig(ProxyConfig config)` | 设置代理配置 | `void` | +| `clearProxyConfig()` | 清除代理配置 | `void` | + +## API使用与介绍 + +### 代理配置 + +```java +// 代理配置类 +public static class ProxyConfig { + private String host; // 代理主机地址 + private int port; // 代理端口号 + private String username; // 代理用户名(可选) + private String password; // 代理密码(可选) + + // 构造方法 + public ProxyConfig(String host, int port) + public ProxyConfig(String host, int port, String username, String password) +} + +// 设置代理 +HttpUtils.ProxyConfig proxyConfig = new HttpUtils.ProxyConfig("proxy.example.com", 8080); +HttpUtils.setProxyConfig(proxyConfig); + +// 设置带认证的代理 +HttpUtils.ProxyConfig authProxy = new HttpUtils.ProxyConfig("proxy.example.com", 8080, "user", "pass"); +HttpUtils.setProxyConfig(authProxy); +``` + +### 参数说明 + +- **url**: 请求的URL地址 +- **body**: 请求体内容,通常为JSON格式 +- **headers**: 自定义请求头,Map类型 +- **config**: 代理配置对象 + +### 使用示例 + +```java +// 完整示例 +public class HttpExample { + public static void main(String[] args) { + try { + // 1. 简单GET请求 + String getResponse = HttpUtils.get("https://jsonplaceholder.typicode.com/posts/1"); + System.out.println("GET响应: " + getResponse); + + // 2. POST请求发送JSON数据 + String jsonBody = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}"; + String postResponse = HttpUtils.post("https://jsonplaceholder.typicode.com/posts", jsonBody); + System.out.println("POST响应: " + postResponse); + + // 3. 带自定义头的请求 + Map headers = new HashMap<>(); + headers.put("Authorization", "Bearer your-jwt-token"); + headers.put("X-Custom-Header", "custom-value"); + + String authResponse = HttpUtils.get("https://api.example.com/protected", headers); + System.out.println("认证响应: " + authResponse); + + // 4. 使用代理 + HttpUtils.ProxyConfig proxyConfig = new HttpUtils.ProxyConfig("127.0.0.1", 8080); + HttpUtils.setProxyConfig(proxyConfig); + + String proxyResponse = HttpUtils.get("https://api.example.com/data"); + System.out.println("代理响应: " + proxyResponse); + + // 清除代理 + HttpUtils.clearProxyConfig(); + + // 5. PUT请求 + String putBody = "{\"id\":1,\"title\":\"updated title\"}"; + String putResponse = HttpUtils.put("https://jsonplaceholder.typicode.com/posts/1", putBody); + System.out.println("PUT响应: " + putResponse); + + // 6. DELETE请求 + String deleteResponse = HttpUtils.delete("https://jsonplaceholder.typicode.com/posts/1"); + System.out.println("DELETE响应: " + deleteResponse); + + } catch (IOException e) { + System.err.println("HTTP请求失败: " + e.getMessage()); + } + } +} +``` + +### 异常处理 + +```java +try { + String response = HttpUtils.get("https://api.example.com/data"); + System.out.println("请求成功: " + response); +} catch (IOException e) { + // 网络连接失败、超时、服务器错误等情况 + System.err.println("请求失败: " + e.getMessage()); +} +``` \ No newline at end of file diff --git a/tml-sdk-java-core/src/readme/JsonUtil.md b/tml-sdk-java-core/src/readme/JsonUtil.md new file mode 100644 index 0000000..54de957 --- /dev/null +++ b/tml-sdk-java-core/src/readme/JsonUtil.md @@ -0,0 +1,125 @@ +# JsonUtil JSON工具类使用说明 + +## 概述 + +`JsonUtil` 是一个基于fastjson2封装的JSON工具类,提供对象与JSON字符串之间的相互转换功能。该工具类设计简洁,支持各种Java对象的序列化与反序列化。 + +## 特性 + +- ✅ **简单易用**:提供简洁的API接口 +- ✅ **高性能**:基于fastjson2,性能优异 +- ✅ **类型安全**:支持泛型,编译时类型检查 +- ✅ **零依赖**:仅依赖fastjson2库 +- ✅ **功能完整**:支持对象转JSON、JSON转对象 +- ✅ **异常处理**:完善的异常处理机制 + +## 快速开始 + +### 基本用法 + +```java +import io.github.timemachinelab.util.JsonUtil; + +// 对象转JSON字符串 +User user = new User("张三", 25); +String jsonString = JsonUtil.toJson(user); +System.out.println("JSON字符串: " + jsonString); + +// JSON字符串转对象 +String json = "{\"name\":\"李四\",\"age\":30}"; +User user2 = JsonUtil.fromJson(json, User.class); +System.out.println("用户名: " + user2.getName()); +``` + +### 处理集合类型 + +```java +// List转JSON +List list = Arrays.asList("apple", "banana", "orange"); +String listJson = JsonUtil.toJson(list); +System.out.println("List JSON: " + listJson); + +// JSON转List +List fruits = JsonUtil.fromJson(listJson, new TypeReference>(){}); +System.out.println("水果列表: " + fruits); +``` + +## API列表 + +| 方法签名 | 描述 | 返回值 | +|---------|------|--------| +| `toJson(Object object)` | 将对象转换为JSON字符串 | `String` | +| `fromJson(String json, Class clazz)` | 将JSON字符串转换为指定类型的对象 | `T` | +| `fromJson(String json, TypeReference typeReference)` | 将JSON字符串转换为指定类型的对象(支持泛型) | `T` | + +## API使用与介绍 + +### 对象转JSON + +```java +// 简单对象 +User user = new User("王五", 28); +String json = JsonUtil.toJson(user); + +// null值处理 +String nullJson = JsonUtil.toJson(null); // 返回 "null" + +// 数组和集合 +int[] numbers = {1, 2, 3, 4, 5}; +String arrayJson = JsonUtil.toJson(numbers); // 返回 "[1,2,3,4,5]" +``` + +### JSON转对象 + +```java +// 基本类型转换 +String userJson = "{\"name\":\"赵六\",\"age\":35}"; +User user = JsonUtil.fromJson(userJson, User.class); + +// 集合类型转换(使用TypeReference) +String listJson = "[\"Java\",\"Python\",\"JavaScript\"]"; +List languages = JsonUtil.fromJson(listJson, new TypeReference>(){}); + +// Map类型转换 +String mapJson = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; +Map map = JsonUtil.fromJson(mapJson, new TypeReference>(){}); +``` + +### 参数说明 + +- **object**: 要转换为JSON的对象,可以为null +- **json**: JSON格式的字符串 +- **clazz**: 目标对象的Class类型 +- **typeReference**: 用于处理泛型类型的TypeReference对象 + +### 使用示例 + +```java +// 完整示例 +public class JsonExample { + public static void main(String[] args) { + // 创建测试对象 + Person person = new Person(); + person.setName("张三"); + person.setAge(30); + person.setEmail("zhangsan@example.com"); + + // 对象转JSON + String json = JsonUtil.toJson(person); + System.out.println("序列化结果: " + json); + + // JSON转对象 + Person restoredPerson = JsonUtil.fromJson(json, Person.class); + System.out.println("反序列化结果: " + restoredPerson.getName()); + + // 处理复杂对象 + Map complexData = new HashMap<>(); + complexData.put("users", Arrays.asList(person)); + complexData.put("count", 1); + complexData.put("success", true); + + String complexJson = JsonUtil.toJson(complexData); + System.out.println("复杂对象: " + complexJson); + } +} +``` \ No newline at end of file