分享个android开发小工具类

博客介绍了如何利用Fastjson库快速将服务器返回的JSON数据转换为对应的Java对象,免去了手动编写Java类字段的繁琐工作。在Java项目中运行特定代码,即可自动生成Java类文件,简化Android开发过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

app与服务器通信大多通过json传递数据,服务器返回的json需要转换成java对象, gson已经轻松帮我们转换成数据对象,可是java类文件的字段还需要我们去一个个写,有点麻烦。今天就给大家带来一个根据json数据自动生成相应的java类文件。在java项目下运行即可。需要引入fastjson.jar。其他内容,有兴趣的朋友都看代码及注释吧!



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class JSONToJavaClass {

    private static final String EXPOSE = "\r\n	@Expose\r\n" ; 
    private static final String PAGEAGE = "package com.model ;\r\n" ; 
    private static final String EXPOSE_PATH = "import com.google.gson.annotations.Expose;\r\n" ; 
    
    public static void main(String[] args){
        String jsonStr = "" ;  //直接指定json字符串
        jsonStr = readString(new File("D:\\json.txt")); //json字符串的文件来源
        String beginKey = "Data" ; //从这从开始转换
        JSONObject json = JSONObject.parseObject(jsonStr); 
        json = json.getJSONObject(beginKey) ; 
        saveClassFile("SomeData" , json ) ; 
    }
    private static String readString(File saveFile){
        InputStream in;
        byte[] buf = null;
        try {
            in = new FileInputStream(saveFile);
            buf = new byte[in.available()] ;
            in.read(buf) ;
            in.close() ;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        if(buf == null){
            return "";
        }
        return new String(buf) ;
    }
    /***
     * 
     * created by czy  2015-4-25  下午9:34:25
     * @param beginKey     文件名,自动在类名后面添加了Model(beginKey+"Model")
     * @param json
     */
    private static void saveClassFile(String beginKey , JSONObject json){
        
        File clsFile = new File("D:\\json_class\\") ; 
        if(!clsFile.exists())
            clsFile.mkdir() ; 
        clsFile = new File(clsFile , beginKey+"Model.java") ; 
        Set set= json.keySet() ; 
        Iterator iter = set.iterator() ; 
        
        StringBuffer headSB = new StringBuffer()  ; 
        headSB.append(PAGEAGE) ; 
        headSB.append(EXPOSE_PATH);
        boolean haveList = false ; 
        StringBuffer topSB = new StringBuffer()  ; 
        topSB.append("public class ").append(beginKey).append("Model{\r\n") ; 
        Object obj = null ; 
        while(iter.hasNext()){
            String key = (String)iter.next() ; 
            obj = json.get(key) ;  
            if(obj instanceof JSONObject ){
                topSB.append(EXPOSE);
                topSB.append("	public ") ;
                topSB.append(key) ; 
                topSB.append("Model ") ; 
                topSB.append(key) ;
                topSB.append(";");
                saveClassFile(key , (JSONObject)obj) ; 
            }
            else if(obj instanceof JSONArray){
                JSONArray array = (JSONArray)obj ; 
                if(array.size()>0){
                    topSB.append(EXPOSE);
                    topSB.append("	public ") ;
                    topSB.append("List<") ;
                    topSB.append(key) ; 
                    topSB.append("Model> ") ; 
                    topSB.append(key) ;
                    topSB.append(";");
                    saveClassFile(key , array.getJSONObject(0)) ;
                    if(!haveList)
                        haveList = true ; 
                }
                continue ; 
            }
            else if(obj instanceof Integer){
                topSB.append(EXPOSE);
                topSB.append("	public int ") ; 
                topSB.append(key) ; 
                topSB.append(";");
            }
            else if(obj instanceof String){
                boolean done = false ; 
                try{
                    Float.valueOf((String)obj) ; 
                    done = true ; 
                }catch(NumberFormatException e){
                }
                if(done){
                    topSB.append(EXPOSE);
                    topSB.append("	public float ") ; 
                    topSB.append(key) ; 
                    topSB.append(";");
                    continue ; 
                }
                String low = ((String)obj).toLowerCase() ; 
                if(low.equals("true")||low.equals("false")){
                    topSB.append(EXPOSE);
                    topSB.append("	public boolean ") ; 
                    topSB.append(key) ; 
                    topSB.append(";");
                    continue ; 
                }
                topSB.append(EXPOSE);
                topSB.append("	public String ") ; 
                topSB.append(key) ; 
                topSB.append(";");
            }
            
        }
        topSB.append("\r\n}") ;
        if(haveList){
            headSB.append("import java.util.List;\r\n") ;
        }
        headSB.append(topSB) ; 
        try {
            OutputStream out = new FileOutputStream(clsFile) ;
            out.write(headSB.toString().getBytes( "UTF-8")) ; 
            out.flush() ; 
            out.close()  ;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值