Gson将JSON转换为实体(Entity)

适应场景

调用接口,需要将返回的不规则json数据,转化为实体

1、ShiftResponse 类(是一个简单的接收数据的JSON格式)

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class ShiftResponse {
    private int code;
    private String msg;
    private List<MqShift> data;
}

2、MaShift实体,(实际接收数据的实体)

存在ShiftResponse的data中,用List的方式存储 

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class MqShift {
    private List<Object> linkObjs;
    private String shiftId;
    private String shiftCode;
    private String name;
    private String shiftRotateCode;
    private String startTime;
    private String endTime;
    private String crtDate;
    private String sortNum;
    private String rentCode;
    private String sname;
}

3、用Gson将请求的数据转换为相应的实体

//调用接口的url
String url = "xxx";
//调接口,获取数据
String request = HttpRequestClient.getRequest(url);
//用Gson将请求到的数据转换为相应的实体
Gson gson = new Gson();
ShiftResponse response = gson.fromJson(request, ShiftResponse.class);
List<MqShift> shiftList = response.getData();

其中HttpRequestClient是个工具类,也可以去网上搜一个,只要可以获取到数据都行

以下是一个HttpRequestClient工具类,可以用的话直接复制,不行的话自己找一各就行

@Component
public class HttpRequestClient {

	private static Logger logger = LoggerFactory.getLogger(HttpRequestClient.class);
	private static CloseableHttpClient httpClient = null;
	private static HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = null;
	private static RestTemplate restTemplate = null;
	static {
		try {
			httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient();
			clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
			restTemplate = new RestTemplate(clientHttpRequestFactory);

		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    // 新添加的测试数据
    public static String doPostJson(String url, String jsonObject, String encoding) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject, headers);
        //打印日志
        logger.info("请求URL {} ", url);
        logger.info("请求参数 {} ", formEntity.toString());
        String  result = restTemplate.postForObject(url, formEntity, String.class);
        logger.info("请求参数 {} ", result);
        return result;
    }
	//get请求
	public static String getRequest(String url, String... variables){

		RestTemplate restTemplate = new RestTemplate();
		return restTemplate.getForObject(url, String.class, (Object[])variables);
	}

	public static String postRequest(String url, String collection){
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		HttpEntity<String> formEntity = new HttpEntity<String>(collection, headers);
		//打印日志
		logger.info("请求URL {} ", url);
		logger.info("请求参数 {} ", formEntity.toString());
		String  result = restTemplate.postForObject(url, formEntity, String.class);
		logger.info("响应{} ", result);
		return result;
	}

	public static String putRequest(String url, String collection){

		String result = "";

		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());

		HttpEntity<String> formEntity = new HttpEntity<String>(collection, headers);

		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, formEntity, String.class);

		Map<String,Object> map=new HashMap<>();
		if(responseEntity.hasBody()){
		  int statusCodeValue = responseEntity.getStatusCodeValue();
		  map.put("stateCode", statusCodeValue);
		  map.put("responsebody", responseEntity.getBody().toString());
			result = JSONObject.fromObject(map).toString();
		}
		return result;
	}

	public static void deleteRequest(String url){
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());

		restTemplate.delete(url);;
	}
	/**
	 * 通过请求体传参
	 * @param url
	 * @param collection
	 */
	public static String deleteRequest(String url,String collection){
		String result = "";
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		HttpEntity<String> formEntity = new HttpEntity<String>(collection, headers);
		logger.info("请求URL {} ", url);
		logger.info("请求参数 {} ", formEntity.toString());
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, formEntity, String.class);
		Map<String,Object> map=new HashMap<>();
		if(responseEntity.hasBody()){
			int statusCodeValue = responseEntity.getStatusCodeValue();
			map.put("stateCode", statusCodeValue);
			map.put("responsebody", responseEntity.getBody().toString());
			result = JSONObject.fromObject(map).toString();
		}
		logger.info("返回 {} ", result);
		return result;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值