• 开发中遇到的问题---【java中常见的JSON格式转换方法】


    import net.sf.json.JSONArray;  //用于集合或数组

    import net.sf.json.JSONObject; //用于对象

    JSONObject object = new JSONObject();

    1.把java 对象列表转换为json对象数组,并转为字符串

    JSONArray array = JSONArray.fromObject(userlist);
      String jsonstr = array.toString();

    2.把java对象转换成json对象,并转化为字符串(好像是map)

    JSONObject object = JSONObject.fromObject(invite);
    String str=object.toString();

    3.把JSON字符串转换为JAVA 对象数组
    String personstr = getRequest().getParameter("persons");
    JSONArray json = JSONArray.fromObject(personstr);
    List<InvoidPerison> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);

    4.把JSON字符串转换为JAVA 对象

    JSONObject jsonobject = JSONObject.fromObject(str);
    PassportLendsEntity passportlends = null;
    try {
    //获取一个json数组
    JSONArray array = jsonobject.getJSONArray("passports");
    //将json数组 转换成 List<PassPortForLendsEntity>泛型
    List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
    for (int i = 0; i < array.size(); i++) {   
    JSONObject object = (JSONObject)array.get(i);  
    PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
    PassPortForLendsEntity.class);

    if(passport != null){
    list.add(passport);
    }
    }

    愿你走出半生,归来仍是少年!
  • 相关阅读:
    LeetCode 39. Combination Sum
    LeetCode 37. Sudoku Solver
    LeetCode 36. Valid Sudoku
    LeetCode 34. Search for a Range
    LeetCode 33. Search in Rotated Sorted Array
    VS2010出现灾难性错误的解决办法
    双系统下利用MbrFix.exe卸载LINUX系统
    VS 与 SQLite数据库 连接
    人月神话阅读笔记2
    关于疫情数据分析web开发2-网页爬取实现
  • 原文地址:https://www.cnblogs.com/hujunwei/p/11312692.html
Copyright © 2020-2023  润新知