当前位置:   article > 正文

通过实体类转换JSON

有没有可以根据实体类生成json
  • RootEntity

    1. `
    2. package com.ithelei;
    3. import java.util.List;
    4. public class RootEntity {
    5. private String errorCode;
    6. private String errorMsg;
    7. private List<UserEntity> data;
    8. public String getErrorCode() {
    9. return errorCode;
    10. }
    11. public void setErrorCode(String errorCode) {
    12. this.errorCode = errorCode;
    13. }
    14. public String getErrorMsg() {
    15. return errorMsg;
    16. }
    17. public void setErrorMsg(String errorMsg) {
    18. this.errorMsg = errorMsg;
    19. }
    20. public List<UserEntity> getData() {
    21. return data;
    22. }
    23. public void setData(List<UserEntity> data) {
    24. this.data = data;
    25. }
    26. @Override
    27. public String toString() {
    28. return "RootEntity [errorCode=" + errorCode + ", errorMsg=" + errorMsg + ", data=" + data + "]";
    29. }
    30. }
    31. `
  • UserEntity

    1. `package com.ithelei;
    2. public class UserEntity {
    3. private String position;
    4. private String userName;
    5. private String webAddres;
    6. public String getPosition() {
    7. return position;
    8. }
    9. public void setPosition(String position) {
    10. this.position = position;
    11. }
    12. public String getUserName() {
    13. return userName;
    14. }
    15. public void setUserName(String userName) {
    16. this.userName = userName;
    17. }
    18. public String getWebAddres() {
    19. return webAddres;
    20. }
    21. public void setWebAddres(String webAddres) {
    22. this.webAddres = webAddres;
    23. }
    24. @Override
    25. public String toString() {
    26. return "UserEntity [position=" + position + ", userName=" + userName + ", webAddres=" + webAddres + "]";
    27. }
    28. }
    29. `
  • JSONTest

  1. `public static void main(String[] args) {
  2. setBeanToJSON();
  3. }
  4. `
  5. `
  6. public static void setBeanToJSON() {
  7. RootEntity rootEntity = new RootEntity();
  8. rootEntity.setErrorCode("0");
  9. rootEntity.setErrorMsg("调用接口成功");
  10. List<UserEntity> data = new ArrayList<UserEntity>();
  11. UserEntity userEntity = new UserEntity();
  12. userEntity.setPosition("技术网站负责人");
  13. userEntity.setUserName("贺雷");
  14. userEntity.setWebAddres("www.ithelei.com");
  15. data.add(userEntity);//集合中装对象
  16. rootEntity.setData(data);
  17. System.out.println(new JSONObject().toJSONString(rootEntity));
  18. }`

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/522947
推荐阅读
相关标签
  

闽ICP备14008679号