Java操作JSON数据(5)--jettison操作JSON数据
jettison是一个简单的JSON处理库,提供JSON和其JSONObject对象相互转化的方法,转为自定义bean时需要再手动将JSONObject对象转为需要的bean。本介绍下jettison的基本使用方法,包括序列化和反序列化;文中所使用到的软件版本:Java 1.8.0_191、jettison 1.4.1。
1、引入依赖
<dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.4.1</version> </dependency>
2、序列化
public static String serialize() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "jack"); jsonObject.put("age", 20); JSONArray address = new JSONArray(); address.put("address1"); address.put("address2"); jsonObject.put("address", address); JSONArray friends = new JSONArray(); Map<String, String> friend1 = new HashMap(){ { put("name", "name1"); put("age", "21"); } }; Map<String, String> friend2 = new HashMap(){ { put("name", "name2"); put("age", "22"); } }; friends.put(friend1); friends.put(friend2); jsonObject.put("friends", friends); String result = jsonObject.toString(); System.out.println(result); return result; }
3、反序列化
public static void deserialize(String json) throws JSONException { JSONObject jsonObject = new JSONObject(json); System.out.println(jsonObject.get("name")); JSONArray address = jsonObject.getJSONArray("address"); System.out.println(address.get(0)); JSONArray friends = jsonObject.getJSONArray("friends"); System.out.println(friends.getJSONObject(0).get("name")); }
4、完整例子
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.abc.demo.general.json; import org.codehaus.jettison.json.*; import java.util.HashMap; import java.util.Map; /** * Jettison使用 */ public class JettisonCase { /** * 序列化 */ public static String serialize() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "jack"); jsonObject.put("age", 20); JSONArray address = new JSONArray(); address.put("address1"); address.put("address2"); jsonObject.put("address", address); JSONArray friends = new JSONArray(); Map<String, String> friend1 = new HashMap(){ { put("name", "name1"); put("age", "21"); } }; Map<String, String> friend2 = new HashMap(){ { put("name", "name2"); put("age", "22"); } }; friends.put(friend1); friends.put(friend2); jsonObject.put("friends", friends); String result = jsonObject.toString(); System.out.println(result); return result; } /** * 反序列化 */ public static void deserialize(String json) throws JSONException { JSONObject jsonObject = new JSONObject(json); System.out.println(jsonObject.get("name")); JSONArray address = jsonObject.getJSONArray("address"); System.out.println(address.get(0)); JSONArray friends = jsonObject.getJSONArray("friends"); System.out.println(friends.getJSONObject(0).get("name")); } public static void main(String[] args) throws Exception { String json = serialize(); deserialize(json); } }