您的位置:首页 > 编程语言 > Java开发

JAVA常用的JSON处理库,常用处理方法

2016-09-12 14:19 417 查看
SON-LIB库处理json
JSON-LIB依赖包



package cn.wangyuan.util;

import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.JSONFunction;
import net.sf.json.JSONObject;

public class JsonUtil {

      public static void main(String[] args) {
      //Map转换json
      Map map=new HashMap();
      map.put("name","json");
      map.put("bool", Boolean.TRUE);
      map.put("int", new Integer(1));
      map.put("arr", new String[]{"a","b"});
      map.put("func","function(i){return this.arr[i]}");
      JSONObject jsonObject=JSONObject.fromObject(map);
      System.out.println(jsonObject);

      //pojo to json   要实现 jopo的getter and setter
   JSONObject pojoToJson=JSONObject.fromObject(new MyBean());
   System.out.println(pojoToJson);
      //获取json对应的元素
   System.out.println("name is "+ pojoToJson.get("name"));

   //json to pojo
   String json = "{\"pojoid\":1,\"name\":\"json1\",\"options\":[\"1\",\"c\"],\"func1\":function(i){ return this.options[i]; }}";
   JSONObject jsonObject2=JSONObject.fromObject(json);
   Object bean=JSONObject.toBean(jsonObject2);
   MyBean myBean=(MyBean) JSONObject.toBean(jsonObject2,MyBean.class);
   System.out.println(myBean.getName());
}
}

FAST-JSON处理json
依赖包
fastjson-1.2.16.jar

package cn.wangyuan.util;
import com.alibaba.fastjson.*;

/**
 *
 *
 * @author tomato
 *
 ************Fastjson是一个Java语言编写的JSON处理器,由阿里巴巴公司开发。
1、遵循http://json.org标准,为其官方网站收录的参考实现之一。
2、功能强大,支持JDK的各种类型,包括基本的JavaBean、Collection、Map、Date、Enum、泛型。
3、无依赖,不需要例外额外的jar,能够直接跑在JDK上。
4、开源,使用Apache License 2.0协议开源。http://code.alibabatech.com/wiki/display/FastJSON/Home
5、具有超高的性能,java世界里没有其他的json库能够和fastjson可相比了。
*************鉴于fastjson优越的性能表现,我建议做如下事情;
1、替换其他所有的json库,java世界里没有其他的json库能够和fastjson可相比了。
2、使用fastjson的序列化和反序列化替换java serialize,java serialize不单性能慢,而且体制大。
3、使用fastjson替换hessian,json协议不必hessian体积大,而且fastjson性能优越,数倍于hessian
4、把fastjson用于memached缓存对象数据。
 *
 */

public class FastJsonUtil {

      public static void main(String[] args) {
      //fastjson pojo to bean
            MyBean myBean=new MyBean();
            String jsonString=JSON.toJSONString(myBean);
            System.out.println(jsonString);

      // fastjson json to string,parse json
            String jsonStr = "{\"JACKIE_ZHANG\":\"张学友\",\"ANDY_LAU\":\"刘德华\",\"LIMING\":\"黎明\",\"Aaron_Kwok\":\"郭富城\"}" ;
            JSONObject jsonObject = JSONObject.parseObject(jsonStr) ;
    //输出结果
            System.out.println(jsonObject);
            System.out.println("li->"+jsonObject.get("LIMING"));
    //输出
          for(java.util.Map.Entry<String,Object> entry : jsonObject.entrySet()){
           System.out.println(entry.getKey()+"-"+entry.getValue()+"\t");
        }
      }
}

[align=left]
[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: