配置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();
}
}
}