当前位置: 移动技术网 > IT编程>开发语言>Java > JSON--List集合转换成JSON对象详解

JSON--List集合转换成JSON对象详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

1. 简单的手动放置 键值对 到jsonobject,然后在put到jsonarray对象里

 list<article> al = articlemng.find(f);
   system.out.println(al.size());
   httpservletresponse hsr = servletactioncontext.getresponse();
   if(null == al){
    return ;
   }
   for(article a : al){
    system.out.println(a.getid()+a.getdescription()+a.gettitle());
   }
   jsonarray json = new jsonarray();
   for(article a : al){
    jsonobject jo = new jsonobject();
    jo.put("id", a.getid());
    jo.put("title", a.gettitle());
    jo.put("desc", a.getdescription());
    json.put(jo);
   }
   try {
    system.out.println(json.tostring());
    hsr.setcharacterencoding("utf-8");
    hsr.getwriter().write(json.tostring());
   } catch (ioexception e) {
    e.printstacktrace();
   }

上述代码jsonarray是引入的org.json.jsonarray包

而用net.sf.json包下jsonarray的静态方法:fromobject(list) 这是网上大多是都是直接用此方法快捷转换json,但是对于hibernate级联操作关联的对象,这个方法就会报错,如果将映射文件中的级联配置去掉就行了。

另外对于list的要求就是其中的元素是字符串或对象,否则json不知道你想要的是什么数据。

<many-to-one name="cmsent" column="comment_tid" class="com.fcms.cms.entity.cmscomment" 
  not-null="false" cascade="delete">

但是级联操作毕竟还是得存在,否则以后数据冗余、多余。

解决方法就是:jsonarray submsgs = jsonarray.fromobject(object, config);

jsonconfig config = new jsonconfig();
  config.setjsonpropertyfilter(new propertyfilter() {
   public boolean apply(object arg0, string arg1, object arg2) {
     if (arg1.equals("article") ||arg1.equals("fans")) {
      return true;
     } else {
      return false;
     }
   }
  });

说明:提供了一个过滤作用,如果遇到关联的对象时他会自动过滤掉,不去执行关联关联所关联的对象。这里我贴出我hibernate中的配置关系映射的代码帮助理解:

<!-- 配置话题和团体之间的关系 -->
  <many-to-one name="article" class="com.fcms.nubb.article" column="article_id"/>
  
  <!-- 配置主题帖与回复的帖子之间的关系 -->
  <set name="submessages" table="sub_message" inverse="true" cascade="all" lazy="false" order-by="date asc">
   <key column="theme_id" />
   <one-to-many class="bbs.po.submessage" />
  </set>

总结:

1. jsonarray submsgs = jsonarray.fromobject(submessages, config);其中config是可选的,当出现上面的情况是可以配置config参数,如果没有上面的那种需求就可以直接使用fromobject(obj)方法,它转换出来的就是标准的json对象格式的数据,如下:

{["attr", "content", ...}, ...]}

2. jsonobject jtmsg = jsonobject.fromobject(thememessage, config);这是专门用来解析标准的pojo,或者map对象的,pojo对象的格式就不用说了,map的形式是这样的{"str", "str"}。

 ----------------------------------------------------------  分割 -------------------------------------------------------------------------------------------

 对于jsonarray和json之前用到想吐了!!!

bean

package com.nubb.bean;

import java.io.serializable;

public class person implements serializable{
 private static final long serialversionuid = 1l;
 private string name;
 private int age;
 private string address;
 public string getname() {
  return name;
 }
 public void setname(string name) {
  this.name = name;
 }
 public int getage() {
  return age;
 }
 public void setage(int age) {
  this.age = age;
 }
 public string getaddress() {
  return address;
 }
 public void setaddress(string address) {
  this.address = address;
 }
 
 
}

jsonutil

package com.nubb.test;

import java.io.ioexception;
import java.nio.file.files;
import java.nio.file.path;
import java.nio.file.standardopenoption;
import java.util.arraylist;
import java.util.list;

import com.alibaba.fastjson.json;
import com.nubb.bean.person;


public class jsonserializer {
  private static final string default_charset_name = "utf-8";

  public static <t> string serialize(t object) {
   return json.tojsonstring(object);
  }

  public static <t> t deserialize(string string, class<t> clz) {
   return json.parseobject(string, clz);
  }

  public static <t> t load(path path, class<t> clz) throws ioexception {
   return deserialize(
     new string(files.readallbytes(path), default_charset_name), clz);
  }

  public static <t> void save(path path, t object) throws ioexception {
   if (files.notexists(path.getparent())) {
    files.createdirectories(path.getparent());
   }
   files.write(path,
     serialize(object).getbytes(default_charset_name),
     standardopenoption.write,
     standardopenoption.create,
     standardopenoption.truncate_existing);
  }
  
  public static void main(string[] args) {
   person person1 = new person();
   person1.setaddress("address");
   person1.setage(11);
   person1.setname("amao");
   
   person person2 = new person();
   person2.setaddress("address");
   person2.setage(11);
   person2.setname("amao");
   
   list<person> lp = new arraylist<person>();
   lp.add(person1);
   lp.add(person2);
   system.out.println(serialize(lp));
  }
  
}

输出:

复制代码 代码如下:

[{"address":"address","age":11,"name":"amao"},{"address":"address","age":11,"name":"amao"}]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网