工具:阿里fastjson、spring的RestTemplete(spring自帶)
maven加載fastjson,版本號和相關(guān)文檔可以到https://github.com/alibaba/fastjson查看
<!--Alijson插件-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
代碼:
public void postApi() {
//目標(biāo)接口地址
String url = "http://xxxxx";
JSONObject postData = new JSONObject();
postData.put("name", "小明");
RestTemplate client = new RestTemplate();
JSONObject json = client.postForEntity(url, postData, JSONObject.class).getBody();
//User是提前創(chuàng)建好的實(shí)體類振亮,將返回的json中的result數(shù)據(jù)轉(zhuǎn)換為User格式
Group group = json.getObject("result", User.class);
System.out.println(group.getName);
}