博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android中json的序列化与反序列化
阅读量:6472 次
发布时间:2019-06-23

本文共 3630 字,大约阅读时间需要 12 分钟。

最近项目中需要在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成员组成的类

转载于:https://www.cnblogs.com/hdjjun/archive/2012/08/30/2663981.html

你可能感兴趣的文章
[LintCode] Longest Substring Without Repeating Characters
查看>>
in-list expansion
查看>>
设计原则(四):接口隔离原则
查看>>
基于react的滑动图片验证码组件
查看>>
iOS快速清除全部的消息推送
查看>>
java单例模式深度解析
查看>>
【学习笔记】阿里云Centos7.4下配置Nginx
查看>>
VuePress手把手一小時快速踩坑
查看>>
dnsmasq安装使用和体验
查看>>
学习constructor和instanceof的区别
查看>>
Vijos P1881 闪烁的星星
查看>>
ABP理论学习之领域服务
查看>>
Qt 控制watchdog app hacking
查看>>
让所有IE支持HTML5的解决方案
查看>>
RDD之五:Key-Value型Transformation算子
查看>>
Windows 搭建Hadoop 2.7.3开发环境
查看>>
python操作mysql数据库实现增删改查
查看>>
percona 5.7.11root初始密码设置
查看>>
Cognitive Security的异常检测技术
查看>>
Impress.js上手 - 抛开PPT、制作Web 3D幻灯片放映
查看>>