• JAVA对象JSON数据互相转换


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

     JSONArray array = JSONArray.fromObject(userlist);

        String jsonstr = array.toString();
     
    2.把java对象转换成json对象,并转化为字符串
     
    JSONObject object = JSONObject.fromObject(invite);
       String str=object.toString();
     
    3.把JSON字符串转换为JAVA 对象数组
     
    String personstr = getRequest().getParameter("persons");
      JSONArray json = JSONArray.fromObject(personstr);
      List<InvoidPerson> 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);
                }  
         }
       //转换PassportLendsEntity 实体类
      passportlends = (PassportLendsEntity)JSONObject.toBean(jsonobject, PassportLendsEntity.class);

      str = "{"lendperson":"李四","lendcompany":"有限公司","checkperson":"李四",

      "lenddate":"2010-07-19T00:00:00","lendcounts":4,"
      passports":[{"passportid":"d","name":"李豫川","passporttype":"K"},
      {"passportid":"K9051","name":"李平","passporttype":"K"},
      {"passportid":"K90517","name":"袁寒梅","passporttype":"K"},
      {"passportid":"K905199","name":"贺明","passporttype":"K"}]}";

     相关包

     

  • 相关阅读:
    当前疫情期间,家里可以适当储备的物资
    35岁改行做程序员,需要勇气和决心
    离婚潮来临,女性在崛起
    摄影作品首先要取悦自己,更要打动他人
    京剧是该阳春白雪还是下里巴人?
    汶川和武汉哪个更让人铭记?
    35以上的女强人不结婚,只用平常待之
    苏州记忆之上班路上偶遇2美女打架
    SAP SD微观研究之销售发票自动生成初探
    Python requests库的使用(二)
  • 原文地址:https://www.cnblogs.com/g-yang/p/6781241.html
Copyright © 2020-2023  润新知