开发中有的表字段特别多,在数据传递过程中要写很多类似实体类的get、set方法把字符串型的数据放到对象里然后,在做存储之类的操作,如果实体的字段少不会觉得多麻烦,但是字段如果有几十个或者更多那么这种简单的get、set方法即废时间又容易出错。如下总结一些java中bean和String之间的转换。
补充:好多数据是json格式的,先把json格式转成字符串也可以进一步转成bean这个,这个比较简单需要的自己实现以下就ok
pom.xml
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --><dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.10.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.10.0</version> </dependency>
UserInfo.java
package .demo; /** * <p> * 的部门信息表。 * </p> * * @author yc * @since 2021-07-23 */ public class UserInfo { private static final long serialVersionUID = 1L; /** * 用户编号 */ private String userId; /** * 用户名称。 */ private String userName; /** * 备注。 */ private String Note; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNote() { return Note; } public void setNote(String note) { Note = note; } @Override public String toString() { return "UserInfo{" + "userId='" + userId + '\'' + ", userName='" + userName + '\'' + ", Note='" + Note + '\'' + '}'; } }
主方法MainFunction.java
package demo; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class MainFunction { public static void main(String[] args){ //实例化一个bean UserInfo userInfo = new UserInfo(); userInfo.setUserId("1"); userInfo.setUserName("张三"); userInfo.setNote("我是张二的弟弟"); // bean和String相互转化需要的类 ObjectMapper ojbectMapper = new ObjectMapper(); //bean 转String String strData = ""; try { strData = ojbectMapper.writeValueAsString(userInfo); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println("bean转String:"+strData); //String 转bean try { UserInfo userInfo1=ojbectMapper.readValue(strData,UserInfo.class); System.out.println("userId:"+userInfo1.getUserId()); System.out.println("userName:"+userInfo1.getUserName()); System.out.println("note:"+userInfo1.getNote()); } catch (Exception e) { e.printStackTrace(); } } }