将list对象转换成json格式

来源:互联网 发布:java函数返回值类型 编辑:程序博客网 时间:2024/05/21 07:03

原文出自:

http://www.cnblogs.com/xmaomao/p/3184542.html

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之前用到想吐了!!!

但是,最近发现个好东西--fastjson (阿里巴巴温少写的一个将Object转为json数据的工具包)

Binary : http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1.jarSource :http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/1.1.1/fastjson-1.1.1-sources.jarSubversion : http://code.alibabatech.com/svn/fastjson/

 

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"}]

 

其中用到的一个jar包可以去下载: http://pan.baidu.com/s/1nCqNV

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 充话费充不进去怎么办 用支付宝充话费没到账怎么办 支付宝充话费未到账怎么办 话费充了不到账怎么办 转转买家不确认收货怎么办 充话费错了怎么办啊 淘宝充值流量没到账怎么办 微信手机充错了怎么办 支付宝充话费没到账怎么办 裤子摔了一个洞怎么办 顾客反应衣服质量不好怎么办 淘宝买的衣服味道很大怎么办 三国杀账号忘了怎么办 宽带连接被删了 怎么办 手机被偷了qq怎么办 手机丢了微信怎么办啊 手机店把手机修坏了怎么办 在手机店买到山寨机手机怎么办 有人在qq群上骂我怎么办 qq群一直有人骚扰怎么办 苹果手机QQ图标不在桌面上怎么办 苹果手机长按不能删除怎么办 qq发的图片过期怎么办 九黎八卦在仓库怎么办 飞猪f2领了万豪银卡没住怎么办 机械键盘摁键冲突怎么办 玩游戏键盘没反应怎么办 玩枪战游戏头晕恶心怎么办 手机看视频不能横屏怎么办 苹果手机安全码忘记了怎么办 信用卡安全码忘记了怎么办 联想电脑管家阻止我安装软件怎么办 word恢复后打开乱码怎么办 苹果手机局域网也登陆不了怎么办 剑三账号冻结7天怎么办 荒野行动无缘无故被限制时间怎么办 电脑打游戏闪屏怎么办 微信下载出现数据包出错怎么办 安卓平板闪退怎么办 剑侠世界2出了1怎么办 苹果手机有木马病毒删除不了怎么办