简体   繁体   English

JSON对象到Java对象的映射是如何完成的?

[英]How the mapping of the JSON object to a Java object is done?

I have tested the REST service with Postman API client which passes the JSON object to the service. 我已经使用Postman API客户端测试了REST服务,该客户端将JSON对象传递给服务。

The JSON object JSON对象

{
    "username" : "user",
    "password" : "pass"
}

The mapping to the Java object is done correctly and returned with Response status 200. 正确完成到Java对象的映射,并以响应状态200返回。

How the JSON object to a Java object mapping is done in operation to the REST service method. JSON对象到Java对象的映射如何在对REST服务方法的操作中完成。

UserCl Class UserCl类别

static class UserCl{

        private String uname;
        private String password;
        private String name;

        public UserCl(){
        }

        public String getName() {
            return name;
        }

        public void setName(String pname) {
            this.name = pname;
        }

        public String getUsername() {
            return uname;
        }
        public void setUsername(String pusername) {
            this.uname = pusername;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String ppassword) {
            this.password = ppassword;
        }

    }

REST service method REST服务方式

@PermitAll
@POST   
@Consumes(MediaType.APPLICATION_JSON)
@Path("/auth")
public Response login(UserCl usr){

    if(usr.getUsername().compareTo("user") == 0 && usr.getPassword().compareTo("pass") == 0){

    String usernameAndPassword = usr.getUsername() + ":" + usr.getPassword(); 

    try {               

            String base64String = Base64Encoder.encode(usernameAndPassword);
            System.out.println(base64String);                               

            return Response.status(200).build();


        } catch (IOException e) {           
            e.printStackTrace();        
            return Response.status(401).build();                
        }   
    }
    else{       
        return Response.status(401)build();
    }

}   

Resteasy uses Jackson by default under the hood. Resteasy默认在引擎盖下使用Jackson。 The basic behavior (as is the case with most serialization frameworks) is to look for JavaBean properties (getters/setters). 基本行为(与大多数序列化框架一样)是寻找JavaBean属性(getters / setters)。 For deserialization, the setters are introspected. 对于反序列化,将对安装程序进行自省。 They should follow JavaBean naming convention . 它们应遵循JavaBean命名约定 If your case 如果你的情况

private String username;

public void setUsername(String string) {}

The set is removed from the method name, and first letter lowercases. set将从方法名称中删除,并且首字母小写。 So setUsername maps to the "username" JSON property. 因此setUsername映射到"username" JSON属性。

When serializing, the getters will be used. 序列化时,将使用吸气剂。 Just like with deserialization, the get is stripped and the first letter lower cased. 就像反序列化一样, get被剥离,首字母小写。 So getUsername will add a "username" property to the resulting JSON. 因此, getUsername会将"username"属性添加到生成的JSON中。

It's also possible to use Jackson annotations to change to property names. 也可以使用Jackson注释更改为属性名称。 For instance 例如

@JsonProperty("name")
private String username;

But this will require you to have Jackson added to your project as a compile-time dependency. 但这需要您将Jackson作为编译时依赖项添加到您的项目中。

EDIT 编辑

Just to add that with Jackson, we don't have to use JavaBean properties. 我想补充的是杰克逊,我们没有使用JavaBean的属性。 Even with public fields, the name of the fields will be used. 即使具有公共字段,也将使用字段名称。 Not really recommended, just thought I'd throw it out there. 不太推荐,只是以为我会把它扔在那里。

Generally it is implemented using reflection. 通常,它是使用反射实现的。 Java has ability to access methods and fields of object using their names. Java能够使用其名称访问方法和对象字段。 This is called reflection. 这称为反射。 In your case JSON library that you are using does this magic. 对于您正在使用的JSON库,此功能就可以实现。

First it finds which class must be instantiated. 首先,它找到必须实例化的类。 It gets it from the type of argument of method login() . 它是从方法login()的参数类型获得的。 It creates instance using code like 它使用如下代码创建实例

Class.forName("UserCl").newInstance()

(that requires public default constructor. Your class does not define any constructor and therefore has one default constructor implicitly.) (这需要公共默认构造函数。您的类未定义任何构造函数,因此隐式具有一个默认构造函数。)

Then it discovers the class UserCl , finds setPassword() and setUsername() and calls them passing values of appropriate JSON attributes. 然后,它发现类UserCl ,找到setPassword()setUsername()并调用它们以传递适当的JSON属性的值。

For more information read about java reflection API. 有关更多信息,请阅读有关Java Reflection API的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM