在JsonObject中包含两次的值?

时间:2016-08-19 14:04:06

标签: java json rest java-ee

我只是想实现一个简单的REST接口,并且在将参数传递给子资源时遇到了问题:

@PUT
@Path("{id}/status2")
public void updateStatus2(@PathParam("id") long id, JsonObject status) {
        System.out.println(status);
}

通过curl传递值:

curl -i -X PUT -H "Content-type: application/json" -H "Accept: application/json" http://localhost:8080/todo/resources/todos/6/status2 -d '{"status":true}'

stdout给了我一个字符串(这是正确的并有效):{"status":true}

现在我在单元测试中做同样的事情:

Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://localhost:8080/todo/resources/todos");

// Todo is a simple POJO just a few strings, value types, getter and setters.
Todo todo = new Todo("foobar0", "foobar1", 1);

// I persist the Todo via post. 
URI createdTodoUri = webTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(todo));

// Create a new object to to pass it via put.
JsonObject statusObject = Json.createObjectBuilder().add("status", true).build();

// Send the JsonObject.
client.target(createdTodoUri).path("/status2").request(MediaType.APPLICATION_JSON_TYPE).put(Entity.json(statusObject));

现在stdou打印出来,我不明白为什么:{"status":{"valueType":"TRUE"}}

按要求提供Todo.java类:

@Entity
@XmlRootElement
public class Todo {

    @Id
    @GeneratedValue
    private Long id;
    private String caption;
    private String description;
    private int priority;
    private boolean done;

    public Todo() {}

    public Todo(String caption, String description, int priority) {
        this.caption = caption;
        this.description = description;
        this.priority = priority;
    }

    public String getCaption() { return caption; }

    public void setCaption(String caption) { this.caption = caption; }

    public String getDescription() { return description; }

    public void setDescription(String description) { this.description = description; }

    public int getPriority() { return priority; }

    public void setPriority(int priority) { this.priority = priority; }

    public Long getId() { return id; }

    public void setId(Long id) { this.id = id; }

    public boolean isDone() { return done; }

    public void setDone(boolean status) { this.done = status; }
}

为什么会有差异,我需要更改哪些以便我的单元测试有效?

1 个答案:

答案 0 :(得分:0)

尝试使用statusObjectJsonWriter写入Json,而不是直接将其直接传递给请求。将它传递给请求会使java序列化其内部结构,但不一样。

Imho最好在服务器和客户端(测试)站点上使用简单的布尔属性或POJO。