发布和接收结果

时间:2018-11-02 22:42:41

标签: java android spring spring-boot

Android空间

void post(Food food)
{
    Gson gson = new Gson();
    String jsonFood = gson.toJson(food);

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    restTemplate.postForEntity(URL, jsonFood, String.class);
}

后端空间

@PostMapping("/food")
public void postFood(@RequestBody String foodJson)
{
    Food food = new GsonBuilder().create().fromJson(foodJson, Food.class);

    String id = createId(food);
    // now how do I send back saying I got this and here is an id?

}

收到后,我想回信说我得到了信息并发回了ID。

2 个答案:

答案 0 :(得分:1)

Spring Boot将使用Jackson将JSON自动转换为隐藏的模型对象

@PostMapping("/food")
public YourResponse postFood(@RequestBody Food food)
{
    String id = createId(food);
    return new YourResponse(id,"hello World");
}

响应对象

 public class YourResponse{
       private String id;
       private String response;
       //.. constructor, getter setter
 }

答案 1 :(得分:0)

您可以创建响应模型

    public class PostFoodResponse{
       private String id;
       private String response;
       //.. constructor, getter setter
    }

在您的代码中创建一个PostFoodResponse集合数据对象,并将该对象作为json响应发送回

@PostMapping("/food")
public String postFood(@RequestBody String foodJson)
{
    Food food = new GsonBuilder().create().fromJson(foodJson, Food.class);

    String id = createId(food);
    // now how do I send back saying I got this and here is an id?
    PostFoodResponse response = new PostFoodResponse(id, "I got this");
    return new GsonBuilder().create().toJson(response);

}