Spring REST - 在@RequestBody中手动解析JSON属性

时间:2014-07-24 10:46:27

标签: java json spring rest jackson

我有实体类:

@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实体 - 它没关系。但我需要在log方法中获取addPerson属性以供其他用途。

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

我该如何解析它?

2 个答案:

答案 0 :(得分:3)

希望您已经拥有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中的任何“额外”字段。

答案 1 :(得分:0)

使用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();
        }
    }
}