zoukankan      html  css  js  c++  java
  • 移动架构-json解析框架

    JSON在现在数据传输中占据着重要地位,相比于xml,其解析和构成都要简单很多,第三方的解析框架也不胜枚举,这里之所以要自定义一个json解析框架,一方面是更好的了解json解析过程,另一方面是有时候需要对解析出来的json数据做转换

    实现的功能

    json转model,model转json

    实现代码

    转化类

    public class FastJson {
        public static final int JSON_ARRAY = 1;
        public static final int JSON_OBJECT = 2;
        public static final int JSON_ERRO = 3;
    
        //调用层调用
        public static Object pareseObject(String json, Class clazz) {
            Object object = null;
            Class<?> jsonClass = null;
            //JSONArray类型
            if (json.charAt(0) == '[') {
                try {
                    object = toList(json, clazz);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (json.charAt(0) == '{') {
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    //反射得到最外层的model
                    object = clazz.newInstance();
                    //得到的最外层的key集合
                    Iterator<?> iterator = jsonObject.keys();
                    //遍历集合
                    while (iterator.hasNext()) {
                        String key = (String) iterator.next();
                        Object fieldValue = null;
                        //得到当前clazz类型的所有成员变量
                        List<Field> fields = getAllFields(clazz, null);
                        for (Field field : fields) {
                            //将key和成员变量进行匹配
                            if (field.getName().equalsIgnoreCase(key)) {
                                field.setAccessible(true);
                                //得到key所对应的值
                                fieldValue = getFieldValue(field, jsonObject, key);
                                if (fieldValue != null) {
                                    field.set(object, fieldValue);
                                }
                                field.setAccessible(false);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            return object;
        }
    
        //得到当前的value值
        private static Object getFieldValue(Field field, JSONObject jsonObject, String key) throws JSONException {
            Object fieldValue = null;
            //得到当前成员变量类型
            Class<?> fieldClass = field.getType();
            if (fieldClass.getSimpleName().toString().equals("int")
                    || fieldClass.getSimpleName().toString().equals("Integer")) {
                fieldValue = jsonObject.getInt(key);
            } else if (fieldClass.getSimpleName().toString().equals("double")
                    || fieldClass.getSimpleName().toString().equals("Double")) {
                fieldValue = jsonObject.getDouble(key);
            } else if (fieldClass.getSimpleName().toString().equals("boolean")
                    || fieldClass.getSimpleName().toString().equals("Boolean")) {
                fieldValue = jsonObject.getBoolean(key);
            } else if (fieldClass.getSimpleName().toString().equals("long")
                    || fieldClass.getSimpleName().toString().equals("Long")) {
                fieldValue = jsonObject.getLong(key);
            } else if (fieldClass.getSimpleName().toString().equals("String")) {
                fieldValue = jsonObject.getString(key);
            } else {
                //判断集合类型和对象类型
                String jsonValue = jsonObject.getString(key);
                switch (getJSONType(jsonValue)) {
                    case JSON_ARRAY:
                        Type fieldType = field.getGenericType();
                        if (fieldType instanceof ParameterizedType) {
                            ParameterizedType parameterizedType = (ParameterizedType) fieldType;
                            //当前类所实现的泛型
                            Type[] fieldArgType = parameterizedType.getActualTypeArguments();
                            for (Type type : fieldArgType) {
                                Class<?> fieldArgClass = (Class<?>) type;
                                fieldValue = toList(jsonValue, fieldArgClass);
                            }
                        }
                        break;
                    case JSON_OBJECT:
                        //fieldClass成员变量类型
                        fieldValue = pareseObject(jsonValue, fieldClass);
                        break;
                    case JSON_ERRO:
                        break;
                }
            }
            return fieldValue;
        }
    
        //获取当前json字符串的类型
        private static int getJSONType(String jsonValue) {
            char firstChar = jsonValue.charAt(0);
            if (firstChar == '{') {
                return JSON_OBJECT;
            } else if (firstChar == '[') {
                return JSON_ARRAY;
            } else {
                return JSON_ERRO;
            }
        }
    
        //解析JsonArray数组
        private static Object toList(String json, Class clazz) throws JSONException {
            List<Object> list = null;
            JSONArray jsonArray = new JSONArray(json);
            list = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                //拿到JSON字符串
                String jsonValue = jsonArray.getJSONObject(i).toString();
                switch (getJSONType(jsonValue)) {
                    case JSON_ARRAY:
                        //外层JSONArray嵌套里面JSONArray
                        List<?> infoList = (List<?>) toList(jsonValue, clazz);
                        list.add(infoList);
                        break;
                    case JSON_OBJECT:
                        list.add(pareseObject(jsonValue, clazz));
                        break;
                    case JSON_ERRO:
                        break;
                }
            }
            return list;
        }
    
        public static String toJson(Object object) {
            //JSON载体
            StringBuilder jsonBuilder = new StringBuilder();
            //判断是否是集合类型
            if (object instanceof List<?>) {
                jsonBuilder.append("[");
                List<?> list = (List<?>) object;
                //获取集合类型
                for (int i = 0; i < list.size(); i++) {
                    //解析成JSONObject类型
                    addObjectToJson(jsonBuilder, list.get(i));
                    if (i < list.size() - 1) {
                        jsonBuilder.append(",");
                    }
                }
            } else {
                addObjectToJson(jsonBuilder, object);
            }
            return jsonBuilder.toString();
        }
    
        //解析单独的JSONObject类型
        private static void addObjectToJson(StringBuilder jsonBuilder, Object o) {
            jsonBuilder.append("{");
            List<Field> fields = new ArrayList<>();
            getAllFields(o.getClass(), fields);
            for (int i = 0; i < fields.size(); i++) {
                //代表get方法
                Method method = null;
                Field field = fields.get(i);
                String fieldName = field.getName();
                Object fieldValue = null;
                //get类型方法
                String methodName = "get" + ((char) (fieldName.charAt(0) - 0x20) + fieldName.substring(1));
                try {
                    //得到method对象
                    method = o.getClass().getMethod(methodName);
                } catch (NoSuchMethodException e) {
                    //is类型方法
                    methodName = "is" + ((char) (fieldName.charAt(0) - 0x20) + fieldName.substring(1));
                    try {
                        method = o.getClass().getMethod(methodName);
                    } catch (NoSuchMethodException e1) {
                    }
                }
                if (method != null) {
                    try {
                        fieldValue = method.invoke(o);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (fieldValue != null) {
                    jsonBuilder.append(""");
                    jsonBuilder.append(fieldName);
                    jsonBuilder.append("":");
                    if (fieldValue instanceof Integer
                            || fieldValue instanceof Double
                            || fieldValue instanceof Long
                            || fieldValue instanceof Boolean) {
                        jsonBuilder.append(fieldValue.toString());
                    } else if (fieldValue instanceof String) {
                        jsonBuilder.append(""");
                        jsonBuilder.append(fieldValue.toString());
                        jsonBuilder.append(""");
                    } else if (fieldValue instanceof List<?>) {
                        addListToBuffer(jsonBuilder, fieldValue);
                    } else {
                        //类类型
                        addObjectToJson(jsonBuilder, fieldValue);
                    }
                    jsonBuilder.append(",");
                }
                if (i == fields.size() - 1 && jsonBuilder.charAt(jsonBuilder.length() - 1) == ',') {
                    jsonBuilder.deleteCharAt(jsonBuilder.length() - 1);
                }
            }
            jsonBuilder.append("}");
        }
    
        //解析集合类型数据
        private static void addListToBuffer(StringBuilder jsonBuilder, Object fieldValue) {
            List<?> list = (List<?>) fieldValue;
            jsonBuilder.append("[");
            for (int i = 0; i < list.size(); i++) {
                addObjectToJson(jsonBuilder, list.get(i));
                if (i < list.size() - 1) {
                    jsonBuilder.append(",");
                }
            }
            jsonBuilder.append("]");
        }
    
        //获取当前Class所有成员变量
        private static List<Field> getAllFields(Class<?> aClass, List<Field> fields) {
            if (fields == null) {
                fields = new ArrayList<>();
            }
            //排除Object类型
            if (aClass.getSuperclass() != null) {
                //拿到当前Class的所有成员变量的Field
                Field[] fieldsSelf = aClass.getDeclaredFields();
                for (Field field : fieldsSelf) {
                    //排除final修饰的成员变量
                    if (!Modifier.isFinal(field.getModifiers())) {
                        fields.add(field);
                    }
                }
                getAllFields(aClass.getSuperclass(), fields);
            }
            return fields;
        }
    }
    

    测试的model类

    public class News {
        private int id;
        private String title;
        private String content;
        private User author;
        private boolean isCancle;
        private List<User> reader;
    
        public News() {
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public User getAuthor() {
            return author;
        }
    
        public void setAuthor(User author) {
            this.author = author;
        }
    
        public boolean isCancle() {
            return isCancle;
        }
    
        public void setCancle(boolean cancle) {
            isCancle = cancle;
        }
    
        public List<User> getReader() {
            return reader;
        }
    
        public void setReader(List<User> reader) {
            this.reader = reader;
        }
    
        @Override
        public String toString() {
            return "News [id=" + id + ", title=" + title + ", content=" + content
                    + ", author=" + author + ", isCancle=" + isCancle + ", reader=" + reader + "]";
        }
    }
    
    public class User {
        private int id;
        private String name;
        private String password;
    
        public User() {
        }
    
        public User(int id, String name, String password) {
            this.id = id;
            this.name = name;
            this.password = password;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
        }
    }
    

    调用测试

    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
        private News news;
        private TextView textView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            textView = findViewById(R.id.text_view);
        }
    
        public void modelToJson(View view) {
            setNews();
            String json = FastJson.toJson(news);
            textView.append(json);
            textView.append("
    
    ");
        }
    
        public void jsonToModel(View view) {
            String json = FastJson.toJson(news);
            News news = (News) FastJson.pareseObject(json, News.class);
            textView.append(news.toString());
            textView.append("
    
    ");
        }
    
        public void cleanText(View view) {
            textView.setText("");
        }
    
        private void setNews(){
            news = new News();
            news.setId(1);
            news.setTitle("Test Title");
            news.setContent("Test Content");
            news.setCancle(true);
            news.setAuthor(createAuthor());
            news.setReader(createReaders());
        }
    
        private static List<User> createReaders() {
            List<User> readers = new ArrayList<User>();
            User readerA = new User();
            readerA.setId(2);
            readerA.setName("Jack");
            readers.add(readerA);
            User readerB = new User();
            readerB.setId(1);
            readerB.setName("Bob");
            readerB.setPassword("123456");
            readers.add(readerB);
            return readers;
        }
    
        private static User createAuthor() {
            User author = new User();
            author.setId(1);
            author.setName("Alen");
            author.setPassword("123456");
            return author;
        }
    }
    

    测试结果如图所示
    效果演示

  • 相关阅读:
    LayoutInflater(布局服务)
    FOTA升级
    APK安装过程及原理详解
    Context类型
    Android应用的persistent属性
    Notification(状态栏通知)详解
    Handler消息传递机制浅析
    Selenium HTMLTestRunner 无法生成测试报告的总结
    【python】远程使用rsa登录sftp,上传下载文件
    02.性能测试中的指标
  • 原文地址:https://www.cnblogs.com/cj5785/p/10664609.html
Copyright © 2011-2022 走看看