【问题标题】:Spring REST - manually parse JSON attributes in @RequestBodySpring REST - 在@RequestBody 中手动解析 JSON 属性
【发布时间】:2014-07-24 10:46:27
【问题描述】:

我有实体类:

@Entity
@Table(name="person")
public class Person implements Serializable {

    @Id @Column(unique=true)
    private int id;

    private String title;

    // getter, setter, constructor,...
}

在控制器中:

@RequestMapping(value="/get/{id}", method=RequestMethod.GET)
    public @ResponseBody Person getPerson(@PathVariable int id) {
        return personManager.findById(id);
    }

@RequestMapping(value="/add", method=RequestMethod.POST)
    public @ResponseBody void addPerson(@RequestBody Person person) {      
        String log = parse_json_from_input("log"); // How can I do it?
        // do something with log
        personManager.save(person);           
    }

我想以 JSON 格式发送附加参数并对其进行解析。如果我执行以下命令,我会得到 Person 实体 - 没关系。但我需要在addPerson 方法中获取log 属性以供其他用途。

curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" \
 -d '{"title":"abc","log":"message..."}' http://localhost:8080/test/add

如何解析它?

【问题讨论】:

    标签: java json spring rest jackson


    【解决方案1】:

    希望您已经拥有 Jackson JSON 依赖项...

    你可以在这里找到它:http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

    我会尝试以下代码:

    ObjectMapper mapper = new ObjectMapper();
    
    @RequestMapping(value="/add", method=RequestMethod.POST)
    public @ResponseBody void addPerson(@RequestBody String json) {     
    
        ObjectNode node = mapper.readValue(json, ObjectNode.class);
    
        if (node.get("log") != null) {
            String log = node.get("log").textValue();
            // do something with log
            node.remove("log"); // !important
        }
    
        Person person = mapper.convertValue(node, Person.class);
        personManager.save(person);           
    }
    

    这应该可以解决问题...

    确保检查并删除任何不在 Person POJO 内的“额外”字段。

    【讨论】:

      【解决方案2】:

      使用 SpringRestTempalge

      RestTemplate restTemplate = new RestTemplate();
      restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
      Person person = get some where
      result = restTemplate.postForObject("http://localhost:8080/test/add", Person, Person.class);
      

      使用 HttpURLConnection

      public class Test {
          public static void main(String[] args) {
              try {
      
                  URL url = new URL("http://localhost:8080/test/add");
                  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                  conn.setDoOutput(true);
                  conn.setRequestMethod("POST");
                  conn.setRequestProperty("Content-Type", "application/json");
      
                  OutputStream outputStream = conn.getOutputStream();
                  String requestMessage = get your  preson json string
                  outputStream.write(requestMessage.getBytes());
                  outputStream.flush();
      
                  if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                      throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
                  }
                  BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                  String output;
                  while ((output = br.readLine()) != null) {
                      System.out.println(output);
                  }
                  conn.disconnect();
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 1970-01-01
        • 2018-01-17
        • 1970-01-01
        相关资源
        最近更新 更多