json jsonlib fastjson jackjosn使用

  以下为网络上收集而来
  • 什么是 Json

JSON(JvaScript Object Notation)(官网网站:http://www.json.org/)是 一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。它基于 JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 的一个子集。 JSON 采用完全独立于语言的文本格式,但是也使用了类似于 C 语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使 JSON 成为理想的数据交换语言。

  • JSON 的两种结构

1.“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表 (hash table),有键列表(keyed list),或者关联数组 (associative array)。 在 Java 语言中,我们可以将它理解成 HashMap。

对象是一个无序的"'名称/值'对"集合。一个对象以"{"(左括号)开始,"}"(右括号)结束。每个“名称”后跟一个":"(冒号);"'名称/值' 对"之间使用","(逗号)分隔。

示例:var json = {"name":"Jack","age":90,"Marray":true};

2. 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(Array 或 List)。

数组是值(value)的有序集合。一个数组以"["(左中括号)开始,"]"(右中括号)结束。值之间使用","(逗号)分隔。

示例:var json = ["Jack","Rose","Tom",89,true,false];

  • fastjson

 一、阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:
速度最快,功能强大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;无依赖,能够直接运行在Java SE 5.0以上版本;支持Android;开源 (Apache 2.0)

Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray 
public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject    
public static final  T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean 
public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray 
public static final  List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合 
public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本 
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本 
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。

二、FastJson解析JSON步骤
 
   A、服务器端将数据转换成json字符串
      首先、服务器端项目要导入阿里巴巴的fastjson的jar包至builtPath路径下(这些可以到fastjson官网下载:http://code.alibabatech.com/wiki/display/FastJSON/Home-zh
JSON <wbr>之FastJson解析然后将数据转为json字符串,核心函数是:
public static String createJsonString(Object value)
    {
        String alibabaJson = JSON.toJSONString(value);
        return alibabaJson;
    }
B、客户端将json字符串转换为相应的javaBean
  首先客户端也要导入fastjson的两个jar包
1、客户端获取json字符串
public class HttpUtil
{
   
    public static String getJsonContent(String urlStr)
    {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

   
    private static String ConvertStream2Json(InputStream inputStream)
    {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonStr;
    }
}

2、使用泛型获取javaBean(核心函数)
    public static T getPerson(String jsonString, Class cls) {
        T t = null;
        try {
            t = JSON.parseObject(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }
public static List getPersons(String jsonString, Class cls) {
        List list = new ArrayList();
        try {
            list = JSON.parseArray(jsonString, cls);
        } catch (Exception e) {
        }
        return list;
    }
public static List> listKeyMaps(String jsonString) {
        List> list = new ArrayList>();
        try {
            list = JSON.parseObject(jsonString,
                    new TypeReference>>() {
            });

        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }




  • jackjson

jackson-core-2.2.3.jar(核心jar包)

jackson-annotations-2.2.3.jar(该包提供Json注解支持)

jackson-databind-2.2.3.jar

//JSON序列化和反序列化使用的User类
import java.util.Date;


public class User {
private String name;
private Integer age;
private Date birthday;
private String email;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}


二、JAVA对象转JSON[JSON序列化]


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;


import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("小民");
user.setEmail("xiaomin@sina.com");
user.setAge(20);

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));

/**
* ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
* ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
* writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
* writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
* writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
* writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
*/
ObjectMapper mapper = new ObjectMapper();

//User类转JSON
//输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json);

//Java集合转JSON
//输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}

三、JSON转Java类[JSON反序列化]

import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}";

/**
* ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
*/
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}

四、JSON注解

Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。

@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。

@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。

@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。

import java.util.Date;
import com.fasterxml.jackson.annotation.*;


public class User {
private String name;

//不JSON序列化年龄属性
@JsonIgnore 
private Integer age;

//格式化日期属性
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birthday;

//序列化email属性为mail
@JsonProperty("mail")
private String email;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}






import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;


import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonDemo {


public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("小民");
user.setEmail("xiaomin@sina.com");
user.setAge(20);

SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirthday(dateformat.parse("1996-10-01"));

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);
//输出结果:{"name":"小民","birthday":"1996年09月30日","mail":"xiaomin@sina.com"}
}
}




  • json-lib

Json-lib 是一个 Java 类库(官网:http://json-lib.sourceforge.net/)可以实现如下功能:

  • 转换 javabeans, maps, collections, java arrays 和 XML 成为 json 格式数据
  • 转换 json 格式数据成为 javabeans 对象

Json-lib 需要的 jar 包

  • commons-beanutils-1.8.3.jar
  • commons-collections-3.2.1.jar
  • commons-lang-2.6.jar
  • commons-logging-1.1.1.jar
  • ezmorph-1.0.6.jar
  • json-lib-2.4-jdk15.jar

 

  • Json-lib 的使用

1. 将 Array 解析成 Json 串。使用 JSONArray 可以解析 Array 类型:

复制代码
package cn.sunzn.json;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;

public class JsonLib {
   public static void main(String[] args) {
       /**
        * 将 Array 解析成 Json 串
        */
       String[] str = { "Jack", "Tom", "90", "true" };
       JSONArray json = JSONArray.fromObject(str);
       System.err.println(json);

       /**
        * 对像数组,注意数字和布而值
        */
       Object[] o = { "北京", "上海", 89, true, 90.87 };
       json = JSONArray.fromObject(o);
       System.err.println(json);

       /**
        * 使用集合类
        */
       List<String> list = new ArrayList<String>();
       list.add("Jack");
       list.add("Rose");
       json = JSONArray.fromObject(list);
       System.err.println(json);

       /**
        * 使用 set 集
        */
       Set<Object> set = new HashSet<Object>();
       set.add("Hello");
       set.add(true);
       set.add(99);
       json = JSONArray.fromObject(set);
       System.err.println(json);
   }
}
复制代码

运行结果如下:

["Jack","Tom","90","true"]
["北京","上海",89,true,90.87]
["Jack","Rose"]
[99,true,"Hello"]

2. 将 JavaBean/Map 解析成 JSON 串。 使用JSONObject 解析:

复制代码
package cn.sunzn.json;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonLib {
   @SuppressWarnings("static-access")
   public static void main(String[] args) {
       /**
        * 解析 HashMap
        */
       Map<String, Object> map = new HashMap<String, Object>();
       map.put("name", "Tom");
       map.put("age", 33);
       JSONObject jsonObject = JSONObject.fromObject(map);
       System.out.println(jsonObject);

       /**
        * 解析 JavaBean
        */
       Person person = new Person("A001", "Jack");
       jsonObject = jsonObject.fromObject(person);
       System.out.println(jsonObject);

       /**
        * 解析嵌套的对象
        */
       map.put("person", person);
       jsonObject = jsonObject.fromObject(map);
       System.out.println(jsonObject);
   }
}
复制代码

运行结果如下:

{"age":33,"name":"Tom"}
{"id":"A001","name":"Jack"}
{"person":{"id":"A001","name":"Jack"},"age":33,"name":"Tom"}

3. 使用 JsonConfig 过虑属性:适用于 JavaBean/Map

复制代码
package cn.sunzn.json;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonLib {
   public static void main(String[] args) {
       JsonConfig config = new JsonConfig();
       config.setExcludes(new String[] { "name" });                      // 指定在转换时不包含哪些属性
       Person person = new Person("A001", "Jack");
       JSONObject jsonObject = JSONObject.fromObject(person, config);    // 在转换时传入之前的配置对象
       System.out.println(jsonObject);
   }
}
复制代码

运行结果如下,在运行结果中我们可以看到 name 属性被过滤掉了:

{"id":"A001"}

4. 将 Json 串转换成 Array:

复制代码
package cn.sunzn.json;

import java.util.Arrays;
import net.sf.json.JSONArray;

public class JsonLib {
   public static void main(String[] args) {
       JSONArray jsonArray = JSONArray.fromObject("[89,90,99]");
       Object array = JSONArray.toArray(jsonArray);
       System.out.println(array);
       System.out.println(Arrays.asList((Object[]) array));
   }
}
复制代码

运行结果如下:

[Ljava.lang.Object;@1e5003f6
[89, 90, 99]

5. 将 Json 串转成 JavaBean/Map:

复制代码
package cn.sunzn.json;

import java.util.Map;

import net.sf.json.JSONObject;

public class JsonLib {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
       /**
        * 将 Json 形式的字符串转换为 Map
        */
       String str = "{\"name\":\"Tom\",\"age\":90}";
       JSONObject jsonObject = JSONObject.fromObject(str);
       Map<String, Object> map = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
       System.out.println(map);

       /**
        * 将 Json 形式的字符串转换为 JavaBean
        */
       str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
       jsonObject = JSONObject.fromObject(str);
       System.out.println(jsonObject);
       Person person = (Person) JSONObject.toBean(jsonObject, Person.class);
       System.out.println(person);
   }
}
复制代码

运行结果如下:

{age=90, name=Tom}
Person [id=A001, name=Jack]

在将 Json 形式的字符串转换为 JavaBean 的时候需要注意 JavaBean 中必须有无参构造函数,否则会报如下找不到初始化方法的错误:

复制代码
Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at net.sf.json.JSONObject.toBean(JSONObject.java:288)
   at net.sf.json.JSONObject.toBean(JSONObject.java:233)
   at cn.sunzn.json.JsonLib.main(JsonLib.java:23)
Caused by: java.lang.NoSuchMethodException: cn.sunzn.json.Person.<init>()
   at java.lang.Class.getConstructor0(Unknown Source)
   at java.lang.Class.getDeclaredConstructor(Unknown Source)
   at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
   at net.sf.json.JSONObject.toBean(JSONObject.java:282)
   ... 2 more

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值