Fastjson

配置Fastjson 的 maven依赖

     <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

springMVC集成 fastjson

需要在 springmvc.xml文件中配置 

    <mvc:annotation-driven>
<!--        消息转换器 不使用默认-->
        <mvc:message-converters register-defaults="false">
<!--配置FastJson 工具中的消息转换器-->
            <bean id="fastJsonConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

将Bean 转化为json格式

    @ResponseBody//如果配置内部资源解析器 一定要添加这个 注解 这样就不会自动去拼接 前后缀了 
    @RequestMapping(value = "/show8")
    public String show8() {
        //使用json的转换工具 将对象转换为 json格式字符串 再返回
        User user = new User();
        user.setUsername("jiuzhou");
        user.setAge(18);
        JSONObject jsonObject = new JSONObject();//创建阿里巴巴fastjson对象
        String s = jsonObject.toJSONString(user);//将object 转化为 json字符串格式
        return s;
    }

实例: 调用免费 API接口 返回值为 JSON 实体类 类型 包含 基本数据类型 与 带泛型list

首先接收到 JSON格式的返回值之后 一定要创建好一个 相应的实体类 来接收

实体类的每一个 属性值 必须与JSON的字段名 相同

还有就是

package com.example.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.cloud.controller.send;
import com.example.cloud.pojo.Weather;
import com.example.cloud.service.weather;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 九州
 * @create 2022/5/9 21:33
 */

@Service
@PropertySource("classpath:weather.properties")
public class weatherImpl implements weather {
//        @Value("${weather.requestURL}")//使用junit 进行测试 无法使用注解注入
//    requestURL 是目标接口 地址
    private String requestURL="https://restapi.amap.com/v3/weather/weatherInfo";
//    @Autowired
//    private com.example.cloud.controller.send send;

    @Test
    @Override
    public void query() throws Exception {

        System.out.println(requestURL);//打印 请求地址查看是否为空
        HttpURLConnection conn; //创建 连接
        BufferedReader reader;//创建缓冲区
        StringBuilder stringBuilder = new StringBuilder();//创建 StringBuilder 对象

        try {
            String strRead;

            URL url = new URL(requestURL);//创建URL对象
            conn = (HttpURLConnection) url.openConnection(); //打开连接
            //使用Get方式请求数据
            conn.setRequestMethod("GET");
            conn.connect();
            //输入流获取返回数据
            InputStream is = conn.getInputStream();

            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((strRead = reader.readLine()) != null) {
                stringBuilder.append(strRead);
            }
            System.out.println("builder" + stringBuilder);
//          此时stringBuilder已经拼接好了 JSON格式的返回值            
//            String.valueOf(stringBuilder)转变为 String  JSON.parseObject 方法 进行反序列化   并且传入 目标类
            Weather myweather = JSON.parseObject(String.valueOf(stringBuilder), Weather.class);
//            Weather myweather = JSON.parseObject(String.valueOf(stringBuilder),new TypeReference<Weather>(){});

            System.out.println("we" + myweather);
            System.out.println("当前温度:"+myweather.getLives().get(0).getTemperature()+"℃");
            System.out.println("查询时间:"+myweather.getLives().get(0).getReporttime());
            System.out.println("今天风向:"+myweather.getLives().get(0).getWinddirection());
            System.out.println("今天天气:"+myweather.getLives().get(0).getWeather());
            send send = new send();
            send.letter(myweather);


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastjsonFastjson2都是JSON库,用于处理JSON格式的数据。 Fastjson2是Fastjson项目的重要升级,旨在为未来十年提供高性能的JSON库。相比于原来的FastjsonFastjson2在性能上有了很大的提升,并且更加安全。它完全删除了autoType白名单,提升了安全性。 在使用上,导入Fastjson2的依赖后,与原来的Fastjson在代码上基本相同。唯一的区别是在Fastjson2中,将`jsonArray.toJavaList`方法转变为`jsonArray.toList`。 总结来说,FastjsonFastjson2都是用于处理JSON数据的库,但Fastjson2是Fastjson的升级版本,提供了更高的性能和更好的安全性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [fastjson2 介绍及使用](https://blog.csdn.net/qq_33697094/article/details/128114939)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Fastjson2你开始使用了吗?来看看源码解析](https://blog.csdn.net/chenxuyuana/article/details/125581066)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值