martin
martin

Reputation: 1787

Spring REST - manually parse JSON attributes in @RequestBody

I have entity class:

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

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

    private String title;

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

In controller:

@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);           
    }

I would like to send additional parameters in JSON and parse it. If I execute below command I get Person entity - it is ok. But I need to get log attribute in addPerson method for other usage.

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

How can I parse it?

Upvotes: 1

Views: 9660

Answers (2)

g00dnatur3
g00dnatur3

Reputation: 1193

Hopefully you have the Jackson JSON dependency already...

you can find it here: http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

I would try the following code:

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);           
}

Thats should do the trick...

make sure you check and remove any "extra" fields that are not inside the Person POJO.

Upvotes: 3

Zaw Than oo
Zaw Than oo

Reputation: 9935

Using 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);

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

Upvotes: 0

Related Questions