其他分享
首页 > 其他分享> > RestTemplate远程调用、JSONObject转Map、Map转对象

RestTemplate远程调用、JSONObject转Map、Map转对象

作者:互联网

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TestMain {

    private  static final Logger log = LoggerFactory.getLogger(TimeTask.class);

    public static void main(String[] args) throws Exception {

        String url = "http://127.0.0.1:8080/busiget/list";

        RestTemplate restTemplate = new RestTemplate();

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

        ArrayList<Object> similarList = new ArrayList<>();
        similarList.add("1");
        similarList.add("2");
        similarList.add("3");

        JSONObject requestMap = new JSONObject();
        requestMap.put("name", "ldj");
        requestMap.put("age", "15");
        requestMap.put("similarList",similarList);

        HttpEntity<JSONObject> entity = new HttpEntity<>(requestMap, headers);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String similarJSON = objectMapper.writeValueAsString(requestMap);
            log.info("similarJSON:{}",similarJSON);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //使用JSONObject,不需要创建实体类VO来接受返参,缺点是别人不知道里面有哪些字段,即不知道有那些key
        JSONObject body1 = restTemplate.postForObject(url, entity, JSONObject.class);

        log.info("body1:{}",objectMapper.writeValueAsString(body1));
        String str = objectMapper.writeValueAsString(body1);
        JSONObject json1 =  JSONObject.parseObject(str).getJSONObject("data");
        Object[] trades = json1.getJSONArray("trades").toArray();
        JSONObject json = JSONObject.parseObject(trades[0].toString());
        Object[] orders  = json.getJSONArray("orders").toArray();
        JSONObject order = JSONObject.parseObject(orders[0].toString());
        //JSONObject转Map
        Map<String, Object> orderMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : order.entrySet()) {
            orderMap.put(entry.getKey(), entry.getValue());
        }
        //System.out.println("map对象:" + userMap.toString());
        //Map转对象
        Orders orders1 = (Orders) MapToObj.mapToObj(orderMap, Orders.class);
        System.out.println(orders1.getBuyer_nick());

/*        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, requestMap, JSONObject.class);
        JSONObject body2 = responseEntity.getBody(); //响应体
        HttpStatus statusCode = responseEntity.getStatusCode(); //状态码
        HttpHeaders headers1 = responseEntity.getHeaders();//获取到头信息*/
    }

}
import java.lang.reflect.Field;
import java.util.Map;

public class MapToObj {
    /**
     * 把source转为target
     * @param source source
     * @param target target
     * @param <T> 返回值类型
     * @return 返回值
     * @throws Exception newInstance可能会抛出的异常
     */
    public static <T> T mapToObj(Map source, Class<T> target) throws Exception {
        Field[] fields = target.getDeclaredFields();
        T o = target.newInstance();
        for(Field field:fields){
            Object val;
            if((val=source.get(field.getName()))!=null){
                field.setAccessible(true);
                field.set(o,val);
            }
        }
        return o;
    }

}

 

public class Orders {
    private String item_meal_name;
    private String pic_path;
    private String seller_nick;
    private String buyer_nick;

    public String getItem_meal_name() {
        return item_meal_name;
    }
    public void setItem_meal_name(String item_meal_name) {
        this.item_meal_name = item_meal_name;
    }

    public String getPic_path() {
        return pic_path;
    }
    public void setPic_path(String pic_path) {
        this.pic_path = pic_path;
    }

    public String getSeller_nick() {
        return seller_nick;
    }
    public void setSeller_nick(String seller_nick) {
        this.seller_nick = seller_nick;
    }

    public String getBuyer_nick() {
        return buyer_nick;
    }
    public void setBuyer_nick(String buyer_nick) {
        this.buyer_nick = buyer_nick;
    }

}

 

标签:Map,String,JSONObject,RestTemplate,nick,import,public
来源: https://www.cnblogs.com/wenbiquan/p/16416261.html