【问题标题】:How to get data from service and database and send post data to server?如何从服务和数据库中获取数据并将发布数据发送到服务器?
【发布时间】:2021-02-01 10:22:51
【问题描述】:

我正在使用 RestTemplate JSON 从服务和数据库中获取数据,然后将 POST 发送到服务器。我在 Postmen 上进行了测试,结果为 200

我的json格式:

{
"senderUser": "myemail@gmail.com",
"data": [
    {
        "actionType": "update-contact",
        "data": {
            "name": "NakiTa  ",
            "lastname": "Isumi",
            "type": 0,
            "title": "ms",
            "passport": "123123",
            "gender": 1,
            "dateOfBirth": "03-01-2021",
            "emails": [
                {
                    "value": "test@gmail.com"
                }
            ],
            "phones": [
                {
                    "value": "0902032618"
                }
            ],
            "addresses": [
                {
                    "addressDetail": "Osaka",
                    "street": "Osaka",
                    "city": "Osaka",
                    "state": "JP",
                    "country": {
                        "code": "jp",
                        "name": "Japan"
                    }
                }
            ],
            "cusFields": [
                {
                    "600f9cb0f02f084bd8a3dcdb": "TEST"
                }                    
            ],
            "customerType": "company"               
        }
    }
]
}

我的班级:

@RequestMapping(value = "/getAllCustomerBasic.do", method = RequestMethod.GET)
public ResponseEntity<List<MyClassMap>> getAllCustomerBasic(@RequestParam Map<String, Object> params,
      HttpServletRequest request) throws Exception {

LOGGER.debug("groupCode : {}", params.get("custId"));

RestTemplate restTemplate = new RestTemplate();

MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
jsonHttpMessageConverter.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
restTemplate.getMessageConverters().add(jsonHttpMessageConverter);

String url = "https://myservice/6670011cbd4a674458d3b26025/90336429462601e7f3326641898fabd9948b349d";
List<MyClassMap> customerList = customerService.getAllCustomerViewBasicInfo(params);            // .selectAccBank(params);

try {

    JSONArray arrayParent = new JSONArray();
    for(int i=0 ; i<customerList.size() ; i++) {
        arrayParent.put(customerList.get(i));
    }

    JSONObject objectParent = new JSONObject();
    objectParent.put("data", arrayParent);

    JSONObject objectChild = new JSONObject();
    objectChild.put("senderUser", "myemail@gmail.com");

    JSONObject objectChildData = new JSONObject();
    objectChildData.put("actionType", "update-contact");

    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());

    HttpEntity<String> entity = new HttpEntity<String>(objectParent.toString(), headers);
    String result = restTemplate.postForObject(url, entity, String.class);

    LOGGER.info(result);
    LOGGER.info("header: " + entity.getHeaders());
    LOGGER.info("body" + entity.getBody());
}

catch (HttpClientErrorException exception) {
    // TODO Auto-generated catch block
    exception.printStackTrace();
}

return ResponseEntity.ok(customerList);         // customerList   jSONObject
}

使用 customerService 将从数据库成功获取数据,但我在构建和检查数据时似乎发生了异常,如下所示:

body{"data":{}}

似乎获取数据为空,无法获取所有数据。如何解决问题?非常感谢

【问题讨论】:

    标签: java json spring spring-boot resttemplate


    【解决方案1】:

    RestTemplate 自动将序列化为 json。您只需定义一个具有 API 期望的相同属性(和相同类型)的 Java 类,并且在 postForObject 方法中指出该对象与您的类相同,而不是 String.class。

    例如,如果您的 MyClassMap 数据与 data json 数组中的元素具有相同的属性,则可能是:

    //You have to add getters and setters and constructor
    public Class Request {
      private String senderUser;
      private List<MyClassMap> data;
    }
    
    ClassRequest request= new ClassRequest();
    request.setData(customerList);
    request.setSenderUser("example");
    HttpEntity<ClassRequest> entity = new HttpEntity<ClassRequest>(request, headers);
    
    String result = restTemplate.postForObject(url, entity, ClassRequest.class);
    

    【讨论】:

    • 嗨@JArgente,我需要像你说的那样创建类似于POJO的新类吗?
    • 或者你能给我更多的细节吗?
    • 是的,您必须创建与您要发送的 json 结构相匹配的 POJO 类,spring 将在 jackson 库的帮助下将其序列化为 json,而无需任何其他代码
    • 所以,你的意思我不使用jackson作为Jsonobject和jsonarray
    • 就是这样,我认为您遇到的问题是因为手动操作您可能犯了一些错误,并且该过程更加繁琐,例如,我可以看到您将 senderUser 属性作为属性objectchild 的属性,但我应该是 objectParent 的属性,因为它与数据处于同一级别。此外,您正在添加 actionType 属性作为您未在代码中使用的 objectChildData 对象的一部分...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2015-10-07
    • 2019-03-31
    • 2015-05-03
    • 2018-05-17
    相关资源
    最近更新 更多