webClient + fastJSON2 获取json格式的数据,同时解析至java class 并 下划线转驼峰

webClient中

.accept(MediaType.APPLICATION_JSON)

决定返回值是什么格式一般情况可以不写,但这里要获取JSON格式的

                .bodyToMono(String.class)

 指定返回类型

fastJSON2中

        Student student = JSON.parseObject(result, Student.class, JSONReader.Feature.SupportSmartMatch);

可以将JSON和java的class属性自动进行匹配

全代码如下:

WebClient webClient = WebClient.create(yourAPI);
    public void tokenToApi(String token) {
        String result = webClient
                .get()
                .uri(uriBuilder -> uriBuilder
                        .path("/your/path/")
                        .queryParam("access_token", token)
                        .build())
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        log.info("学生:{}",result);

        // fastJSON JSON 反序列化 + 转驼峰命名
        Student student = JSON.parseObject(result, Student.class, JSONReader.Feature.SupportSmartMatch);
        log.info("反序列化:{}", student);

WebClient 中使用 Fastjson,您需要将 Fastjson 添加为项目的依赖。可以在项目的 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> ``` 然后,您可以使用 WebClient 发起 HTTP 请求,并使用 Fastjson解析响应的 JSON 数据。下面是一个示例代码: ```java import com.alibaba.fastjson.JSON; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.client.WebClient; public class FastjsonExample { public static void main(String[] args) { WebClient webClient = WebClient.create(); // 发起 GET 请求 webClient.get() .uri("https://api.example.com/data") .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .retrieve() .bodyToMono(String.class) .subscribe(response -> { // 使用 Fastjson 解析 JSON 响应 DataObject dataObject = JSON.parseObject(response, DataObject.class); System.out.println(dataObject); }); } private static class DataObject { // 定义与 JSON 结构对应的数据模型 private String name; private int age; // getter 和 setter 方法 // ... } } ``` 上述示例中,我们使用 WebClient 发起了一个 GET 请求,并指定接受 JSON 格式的响应。通过调用 `bodyToMono(String.class)` 方法,我们将响应换为字符串类型。然后,使用 Fastjson 的 `parseObject` 方法将 JSON 字符串解析数据模型对象 `DataObject`。 请注意,示例中的 `DataObject` 类需要根据实际 JSON 结构进行定义,以便与 JSON 数据正确映射。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值