android中json的序列化與還原序列化

來源:互聯網
上載者:User

最近項目中需要在android中將對象轉為json字串以及還原序列化為對象,查閱了android sdk文檔後,發現android中沒有類似C#裡DataContractJsonSerializer的類,想想需求也不算複雜,就自己寫了兩個方法解決,代碼如下:

public static String getJson(Object objSource){
        try{
            Object object = getJsonObject(objSource);
            if(object == null)
                return "";
            return ((JSONObject)object).toString();
        }catch(Exception err){
            Log.e(TAG, "getJson exception:"+err.getMessage());
            return "";
        }
    }
    
    private static Object getJsonObject(Object objSource) throws Exception{
        if(objSource != null){            
            Class<?> objClass = objSource.getClass();
            if(objClass.getPackage().getName().startsWith(PackageString)){
                JSONObject jsonObject = new JSONObject();
                Field[] publicFields = objClass.getFields();
                Object val;            
                for(Field field : publicFields){
                    val = field.get(objSource);
                    if(val != null){    
                        Class<?> valClass = val.getClass();
                        if(valClass.isArray()){
                            JSONArray array = new JSONArray();
                            int length = Array.getLength(val);
                            for(int i = 0; i<length; i++){
                                array.put(getJsonObject(Array.get(val, i)));
                            }
                            jsonObject.put(field.getName(), array);
                        }else if(valClass.equals(ArrayList.class)){
                            ArrayList<?> aList = ArrayList.class.cast(val);
                            Iterator<?> iterator = aList.iterator();
                            JSONArray array = new JSONArray();
                            while (iterator.hasNext()) {
                                array.put(getJsonObject(iterator.next()));                                
                            }
                            jsonObject.put(field.getName(), array);
                        }else{
                            jsonObject.put(field.getName(),getJsonObject(val));
                        }
                    }else{
                        jsonObject.put(field.getName(), null);
                    }                
                }
                return jsonObject;
            }else{
                return objSource;
            }
        }
        return null;
    }
    
    
    public static Object parseJson(Class<?> targetClass,String jsonString){
        try{
            Object object = targetClass.newInstance();
            JSONObject jsonObject = new JSONObject(jsonString);
            String key;
            Class<?> fieldClass;
            Object element;
            Class<?> elementType;
            Field[] fields = targetClass.getFields();
            
            for(Field field : fields){
                
                key = field.getName();
                fieldClass = field.getType();
                if(fieldClass.equals(ArrayList.class)){
                    String genericType = field.getGenericType().toString();
                    if(genericType.indexOf("<") > 0){
                        genericType = genericType.substring(genericType.indexOf("<")+1,genericType.lastIndexOf(">"));    
                    }
                    ArrayList<Object> aList = new ArrayList<Object>();
                    JSONArray array = jsonObject.getJSONArray(key);
                    int length = array.length();
                    if(genericType.startsWith(PackageString)){
                        elementType = Class.forName(genericType);
                        Field[] elementFields = elementType.getFields();
                        JSONObject subJsonObject;
                        for(int i=0;i<length;i++){
                            element = elementType.newInstance();
                            subJsonObject = array.getJSONObject(i);
                            for(Field subField : elementFields){
                                subField.set(element, subJsonObject.get(subField.getName()));
                            }
                            aList.add(element);                        
                        }
                    }else{
                        for(int i=0;i<length;i++){
                            aList.add(array.get(i));
                        }
                    }
                    field.set(object, aList);
                    
                }else if(fieldClass.isArray()){
                    JSONArray array = jsonObject.getJSONArray(key);
                    int length = array.length();
                    String arrayTypeName = fieldClass.getComponentType().getName();
                    Object[] objArray = new Object[length];
                     
                    if(arrayTypeName.startsWith(PackageString)){
                        elementType = Class.forName(arrayTypeName);
                        Field[] elementFields = elementType.getFields();
                        JSONObject subJsonObject;
                        for(int i=0;i<length;i++){
                            element = elementType.newInstance();
                            subJsonObject = array.getJSONObject(i);
                            for(Field subField : elementFields){
                                subField.set(element, subJsonObject.get(subField.getName()));
                            }
                            objArray[i] = element;                        
                        }
                    }else{
                        for(int i=0;i<length;i++){
                            objArray[i] = array.get(i);
                        }
                    }
                    field.set(object, objArray);
                    
                }else{
                    field.set(object, jsonObject.get(key));
                }
            }
            return object;
        }catch(Exception err){
            Log.e(TAG, "parseJson exception:"+err.getMessage());
            return null;
        }
    }

 支援基本類型、數組、ArrayList成員組成的類

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.