1

有人可以解释下面的代码吗?

我知道 RESTEasy 客户端和 Jersey AuthenticationFeature ......但这意味着 SimpleOperation 类和它是什么 API?

HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest("admin", "admin");
Client client = ClientBuilder.newClient();
client.register(feature);
Entity<SimpleOperation> operation = Entity.entity(
    new SimpleOperation("read-resource", true, "subsystem", "undertow", "server", "default-server"),
    MediaType.APPLICATION_JSON_TYPE);
WebTarget managementResource = client.target("http://localhost:9990/management");
String response = managementResource.request(MediaType.APPLICATION_JSON_TYPE)
    .header("Content-type", MediaType.APPLICATION_JSON)
    .post(operation, String.class);
System.out.println(response);

来自:https ://docs.jboss.org/author/display/WFLY10/The+HTTP+management+API

4

1 回答 1

3

如果您找不到SimpleOperation类是什么,或者它只是文档的一些编造类,您可以简单地创建自己的类。它只是 JSON 序列化程序用来序列化为 JSON 的简单 POJO。如果您不熟悉 JSON/POJO 映射,这里有一些提示

  • JSON 对象(通常)映射到 Java POJO 类。所以{ }会映射到

    class SomeClass
    
  • JSON 属性映射到 Java bean 属性。例如,如果您有一个 JSON 属性firstName,那么您将需要一个带有 getter 和 setter 的字段,其中 getter 和 setter 与 JSON 属性的名称匹配(带有 get/set 前缀和首字母大写)

    class SomeClass {
        private String firstName;
        public String getFirstName() { return firstName; }
        public void setFirstName(String firstName) { this.firstName = firstName }
    }
    

    因此,如果您要new SomeClass("Joao")作为实体发送,它将序列化为

    {"firstName": "Joao"}
    

话虽如此,如果您知道需要发送的 JSON 格式,那么创建自己的 POJO 应该不会太难。

其他一些类型映射:

  • JSON 数组通常映射到List. 因此,如果有["hello", "world"],您可以将其映射到List<String>.

  • 或者,如果您有一个 JSON 对象的 JSON 数组,例如[{"prop":"value"}, {"prop":"value"}],您可以将其映射到List<SomeType>

  • Boolean java property getter可以遵循更广泛的命名约定,即getProperty, isProperty,hasProperty

这几乎就是我能想到的所有基础知识。例如,查看您提供的链接中的示例请求之一

{
  "operation":"read-resource", 
  "include-runtime":"true",
  "recursive":"true", 
  "address":["subsystem","undertow","server","default-server"]
}

你可以把它映射到一个 POJO 像

public class SimpleOperation {
    private String operation;
    @JsonProperty("include-runtime")
    private boolean includeRuntime;
    public boolean recursive;
    private List<String> address;

    public SimpleOperation(String operation, boolean includeRuntime, 
                          boolean recursive, String... address) {
        this.operation = operation;
        this.includeRuntime = includeRuntime;
        this.address = Arrays.asList(address);
    }

    // getters and setters.
}

@JsonProperty是为了让 Jackson 序列化程序知道如何设置 JSON 属性名称。它将默认脱离我上面提到的命名约定,但它不知道-在名称中使用 ,所以我们明确告诉它应该是什么属性名称。

然后你可以做

new SimpleOperation("read-resource", true, "subsystem", "undertow", "server", "default-server")

并且应该序列化为上面的JSON

于 2016-04-21T15:41:20.687 回答