1、发送http请求:
HttpPost httpPost =newHttpPost(发送的URL);
UrlEncodedFormEntity entity =newUrlEncodedFormEntity(formparams,"UTF-8");
httpPost.setEntity(entity);
其中,formparams为发送的list对象。
2、回收response请求,得到结果:
HttpClienthttpClient =newDefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
获取reponse的返回码:httpResponse.getStatusLine().getStatusCode() = 200
3、获取请求(HttpServletRequestrequest)里格式为Map的key的值
Map params =newHashMap();
String batchNo = request.getParameter("batchNo");
java转对象:
UcfPayOfReturnParameterSynVo resData = gson.fromJson(resultXml,UcfPayOfReturnParameterSynVo.class);//得到对象
其中:resultXml为string类型的json串。
4、类型为string的json,转为JSONArray
JSONArray jsonArray = com.alibaba.fastjson.JSONObject.parseArray(orders);
jsonarray本身就是一个List,所以转换成list对象如下:
List orderList =new ArrayList<>();
UcfNoticeOrdersDto data =newUcfNoticeOrdersDto();
for(inti =0;i < jsonArray.size();i++) {
data = com.alibaba.fastjson.JSONObject.parseObject(jsonArray.get(i).toString(),UcfNoticeOrdersDto.class);
orderList.add(data);
}
5、使用Gjson,json与对象相互转化
使用Gson轻松将Java对象转化为json格式
String json = gson.toJson(Object);//得到json形式的字符串
User user = gson.fromJson(json,User.class);//得到对象
转化成list
[csharp]view plaincopyprint?
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lc.function.Action;
import com.lc.models.Groups;
public class MapSearch {
private void ParseData(String _data)
{
Gson gson = new Gson();
List ps = gson.fromJson(_data, new TypeToken>(){}.getType());
System.out.println(ps.get(0).getGroup_name());
}
}
6、list对象转换成json,并替换json中的“
Gson gson =newGson();
String ordersStr = gson.toJson(ordersList);
String ordersReplace = ordersStr.replaceAll("\"","'");
7、遍历一个list,将list的值放在一个map里:
formparams.add(newBasicNameValuePair("orders",ordersReplace));
Map map =newHashMap<>();
for(NameValuePair formParam : formparams) {
String keyOfFormParam = formParam.getName();
String value = formParam.getValue();
map.put(keyOfFormParam,value);
}
8、转换成json格式
/**
*转换成json格式
* @paramrequest
* @return
*/
privateStringgetRequestBodyOfJson(HttpServletRequest request) {
String json =null;
InputStream is =null;
BufferedReader br =null;
try{
is = request.getInputStream();
StringBuilder messageBuffer =newStringBuilder();
br =newBufferedReader(newInputStreamReader(is,"utf-8"));
String line =null;
while((line = br.readLine()) !=null) {
messageBuffer.append(line);
}
json = messageBuffer.toString();
LOGGER.info("----------接收JSON="+ json);
}catch(Exception e) {
LOGGER.error("从request获取请求参数异常",e);
}finally{
try{
if(br !=null) {
br.close();
}
}catch(Exception e) {
LOGGER.error("关闭BufferedReader出现异常",e);
}
try{
if(is !=null) {
is.close();
}
}catch(Exception e) {
LOGGER.error("关闭InputStream出现异常",e);
}
}
return json;
}
9、String 类型的json转map
String json = "";
Map productMap = JsonUtils.jsonToBean(json,Map.class);