zoukankan      html  css  js  c++  java
  • 转载:java方式的将java对象以及list或者map转化为json数据 .

    转载网址:http://blog.csdn.net/gudong2945/article/details/6415449

    public class Test {
    public static void main(String[] args) {
    //当是对象的时候
    Student student = new Student();
    student.setAge(18);
    student.setName("zhangsan");
    student.setSex("male");
    JSONObject jsonObject = JSONObject.fromObject(student);
    System.out.println(jsonObject);//输出{"age":18,"name":"zhangsan","sex":"male"}
    //当是数组或list的时候
    Student[] stus = new Student[5];
    List<Student> stuList = new ArrayList<Student>();
    for (int i = 0; i < stus.length; i++) {
    stus[i] = new Student();
    stus[i].setAge(i*10+8);
    stus[i].setName("zhang"+i);
    stus[i].setSex("male");
    //添加到list,一会儿用
    stuList.add(stus[i]);
    }
    JSONArray jsonArray = JSONArray.fromObject(stus);
    System.out.println(jsonArray);//和下面打印的结果相同
    //结果:[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"age":48,"name":"zhang4","sex":"male"}]
    JSONArray jsonArrayFromList = JSONArray.fromObject(stuList);
    System.out.println(jsonArrayFromList);//和上面打印的结果相同
    //当既有对象又有数组的时候
    Map<String,Object> map = new HashMap<String,Object>();
    Teacher teacher = new Teacher();
    teacher.setAge(30);
    teacher.setName("laoshi");
    teacher.setSex("male");
    map.put("teacher", teacher);
    map.put("student", stuList);
    JSONObject jsonObjectFromMap = JSONObject.fromObject(map);
    System.out.println(jsonObjectFromMap);
    //结果:
    //{"student":[{"age":8,"name":"zhang0","sex":"male"},{"age":18,"name":"zhang1","sex":"male"},{"age":28,"name":"zhang2","sex":"male"},{"age":38,"name":"zhang3","sex":"male"},{"age":48,"name":"zhang4","sex":"male"}],"teacher":{"age":30,"name":"laoshi","sex":"male"}}
    }
    }

  • 相关阅读:
    旁友数独会伐啦?python秒解数独了解下伐啦?
    趁老王不在,和隔壁邻居斗斗地主,比比大小
    ll字段 详解 文件权限
    etc/pass命令列表
    maven配置
    linux常用汇总
    Tomcat学习笔记
    JavaEE高级-Hibernate学习笔记
    JavaEE高级-通用Mapper学习笔记
    jQueryrocket
  • 原文地址:https://www.cnblogs.com/lraa/p/2841787.html
Copyright © 2011-2022 走看看