/java/

Jersey example response.

2013-08-27 23:45:39

@GET
@Path("/r/f")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ResponseDto getResponseFalse(){
    ResponseDto responseDto = new ResponseDto(false);
    responseDto.addErrors(new ResponseItemDto("name", "Field name is empty."));
    responseDto.addErrors(new ResponseItemDto("lastname", "Field lastname is empty."));
    return responseDto;
}

ResponseDto.java

package pl.btbw.dto;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

@XmlRootElement(name = "response")
public class ResponseDto {

    private boolean valid;

    @XmlElement(name = "messages")
    private List

<responseitemdto> messages;

    public ResponseDto() {
    }

    public ResponseDto(boolean b) {
        this.valid = b;
    }

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    @XmlTransient
    public List<responseitemdto> getErrors() {
        return messages;
    }

    public void setErrors(List<responseitemdto> errors) {
        this.messages = errors;
    }

    public void addErrors(ResponseItemDto error) {
        if (this.messages == null) {
            this.messages = new ArrayList<responseitemdto>();
        }
        this.messages.add(error);
    }
}

ResponseItemDto.java

package pl.btbw.dto;

import javax.xml.bind.annotation.XmlType;

@XmlType(name="message")
public class ResponseItemDto {

    private String key;

    private String value;

    public ResponseItemDto() {
    }

    public ResponseItemDto(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}