Java 將對象解析成JSON格式 無外掛程式形式

來源:互聯網
上載者:User

自己寫的一段解析的代碼:

解析後的字元效果:

{'Student':{id:1,string:'這是一個人',address:'長沙',{'Human':{id:1,type:'黃種人',{'Product':{id:1,name:'IPHONE5',description:'產品的描述資訊',img:'圖片',stock:12,bidPrice:12.0,price:3000.0,null,null,supplier:'美國',addTime:'1970-01-01 08:00:00.1'}}}{'list':{'Student':{id:1,string:'這是一個人',address:'長沙',{'Human':{id:1,type:'黃種人',{'Product':{id:1,name:'IPHONE5',description:'產品的描述資訊',img:'圖片',stock:12,bidPrice:12.0,price:3000.0,null,null,supplier:'美國',addTime:'1970-01-01 08:00:00.1'}}},{'Human':{id:1,type:'黃種人',{'Product':{id:1,name:'IPHONE5',description:'產品的描述資訊',img:'圖片',stock:12,bidPrice:12.0,price:3000.0,null,null,supplier:'美國',addTime:'1970-01-01 08:00:00.1'}}

不過對象的欄位有多少個子物件可以解析,用了遞迴進行解析。

在調用此類進行解析的時候,Bean 的欄位請全部使用封裝類,否則會出現異常。

代碼部分:

主要解析代碼:

BeanUtil.java

package org.dreamer.data.util;import java.lang.reflect.Field;/** * 返回該對象的所有欄位值 * @author Pan * */public class BeanUtil {/** * 返回當前對象的字串 */public String toString() {return getString(this);}/** * 返回指定對象的字串 * @param object * @return */public String getString(Object object){if(object==null)return "null";String str = "";str+="{'"+object.getClass().getSimpleName()+"':{";Class cl = object.getClass();Field[] fields = cl.getDeclaredFields();boolean sign = true;String s = ",";for (Field field : fields) {field.setAccessible(true);//設定成可訪問的//判斷欄位是不是對象if (sign) {s = "";sign = false;} else {s = ",";}try {TypeCollection types=new TypeCollection();boolean result=types.check(field.get(object));//如果不是基礎類型就用遞迴求出所有的子物件if(!result){str+=s+getString(field.get(object));continue;}Object value=JSONHelper.check(field.get(object))?"'"+field.get(object)+"'":field.get(object);str += s + field.getName() + ":" + value;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}str+="}";return str;}}

Json助手類:

JSONHelper.java

package org.dreamer.data.util;import java.sql.Timestamp;public class JSONHelper {/** * 檢查是否是String和Timestamp類型 * @param object * @return */public static boolean check(Object object){return object instanceof String || object instanceof Timestamp;}}

JSONSupport.java

調用的話就調用這個類,這個類可以解析對象,和對象數組

package org.dreamer.data.json;import java.util.Collection;import org.dreamer.data.util.BeanUtil;/** * JSON 解析對象 * 在解析對象的時候,如果發現對象的欄位類型不是基礎類型 * 那麼將調用遞迴進行迴圈解析 * @author Pan * */public class JSONSupport {/** * 將對象解析成JSON字串 * @param object * @return */public static String parseString(Object object){//檢查對象是否繼承了BeanUtil類String superClass=object.getClass().getSuperclass().getCanonicalName();BeanUtil beanUtil=new BeanUtil();//如果檢測到對象已經繼承了BeanUtil類,那麼將直接調用對象的toString方法//BeanUtil 已經對之類的toString進行重新//所以無需進行重複的操作if(beanUtil.getClass().getCanonicalName().equals(superClass)){return object.toString();}return beanUtil.getString(object);}/** * 解析一個集合對象 * @param collection * @return */public static String parseCollection(Collection collection){String str="{'list':";boolean sign=true;String charStr=",";for (Object object : collection) {if(sign){charStr="";sign=false;}else {charStr=",";}str+=charStr+parseString(object);}return str+="";}}

TypeCollection.java 這一個類非常的重要 因為要判斷解析的對象是不是基本類型,如果是基本的一些資料類型 就不進行解析。

package org.dreamer.data.util;import java.lang.reflect.Field;import java.sql.Timestamp;/** * 基礎類型集合 * @author Pan * */public class TypeCollection {/** * 基礎資料類型的封裝類 */private Integer integer;private Double double1;private Float float1;private Long long1;private String string;private Character character;private Boolean boolean1;private Short short1;private Timestamp timestamp;/** * 檢查該對象是不是基礎資料類型 * @param object * @return */public boolean check(Object object) {if(object==null)return false;// 擷取當前類的Class對象的欄位集合Field[] fields = this.getClass().getDeclaredFields();for (Field field : fields) {// 設定欄位可訪問field.setAccessible(true);// 擷取欄位類型來比較if (field.getType().getName().equals(object.getClass().getName())) {return true;}}return false;}}

非常容易就解析成JSON了,比起網上臃腫的外掛程式,這方便了少許。

下面給一段我測試的代碼:

請勿直接運行,會報錯。

package com.domain;import java.sql.Timestamp;import java.util.ArrayList;import java.util.List;import org.dreamer.data.json.JSONSupport;import org.dreamer.data.util.BeanUtil;import org.dreamer.data.util.TypeCollection;import com.pan.action.Product;import com.pan.beans.User;public class JSONTest {public static void main(String[] args) throws Exception {Student student=new Student();student.setAddress("長沙");Product product=new Product();product.setAddTime(new Timestamp(100));product.setBidPrice(12d);product.setDescription("產品的描述資訊");product.setId(1);product.setImg("圖片");product.setName("IPHONE5");product.setPrice(3000d);product.setStock(12);product.setSupplier("美國");Human human=new Human();human.setProduct(product);human.setId(1);human.setType("黃種人");student.setHuman(human);student.setId(1);student.setString("這是一個人");System.out.println(student.getClass().getSuperclass().getCanonicalName());List list=new ArrayList();list.add(student);list.add(human);System.out.println(student);System.out.println(JSONSupport.parseCollection(list));}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.