Android学习(二):解析JSON,GSON,FASTJSON;JDBC编程

一、android使用JSON
JSON数据格式如下形式(以键值对的形式存在):
{
    "students":
    [
        {"name":"jack","age":10},
        {"name":"Lucy","age":40}
    ]
}
·解析JSON格式如下例子代码:
·1.首先定义Person类,创建Person.java
package com.qianfeng.domain;
public class Person {
    private int age; 
    private String name;
    public Person() { // TODO Auto-generated constructor stub }
    public Person(int age, String name) { super(); this.age = age; this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    @Override 
    public String toString() { return "Person [age=" + age + ", name=" + name + "]"; }
}
·2.JsonList数据,创建JsonList.java
package com.qianfeng.service;
import java.util.ArrayList;
import java.util.List;
import com.qianfeng.domain.Person;
public class JsonList {
    public JsonList() {}
    public static List<Person> getList() {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person(1002,"李四2"));
        list.add(new Person(1003,"李四3"));
        list.add(new Person(1001,"李四1"));
        return list;
    }
    public static Person getPerson(){
        return new Person(1002,"李四2"); 
    }
}
·3.JSON解析程序,创建JsonTools.java
package com.qianfeng.service;
import java.util.ArrayList;
import java.util.List;
import com.qianfeng.domain.Person;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class JsonTools {
    public JsonTools() {}
    public static String getString(Person person) {
        JSON json = JSONSerializer.toJSON(JsonList.getPerson());
        return json.toString();
    }
    public static Person getPerson(String msgString) {
        Person person = new Person();
        JSONArray array = new JSONArray();
        array.add(msgString);
        JSONObject obj = array.getJSONObject(0);
        // System.out.println(obj.get("age"));
        // System.out.println(obj.get("name"));
        person.setAge(obj.getInt("age"));
        person.setName(obj.getString("name"));
        return person;
    }
    public static String getListString(List<Person> listPersons) {
        JSON json = JSONSerializer.toJSON(listPersons);
        return json.toString();
    }
    /**
     * 将一个json格式的字符串转换成行对应的对象
     * @param str
     * @return
     */
    public static List<Person> getPersons(String str) {
        List<Person> list = new ArrayList<Person>();
        JSONArray array = new JSONArray();
        array.add(str);
        JSONArray array2 = array.getJSONArray(0);
        for (int i = 0; i <array2.size(); i++) {
            JSONObject jsonObject =  array2.getJSONObject(i);
            Person person = new Person();
            person.setAge(jsonObject.getInt("age"));
            person.setName(jsonObject.getString("name"));
            list.add(person);
        }
        return list;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // JSON json = JSONSerializer.toJSON(JsonList.getList());
        // System.out.println(getString(new Person(23,"jack")));
        // System.out.println(getPerson("{'age':1002,'name':'李四2'}").toString());
        // System.out.println(getListString(JsonList.getList()));
        String msgString = "[{'age':1002,'name':'李四2'},{'age':1003,'name':'李四3'},{'age':1001,'name':'李四1'}]";
        List<Person> lPersons = getPersons(msgString);
        for(Person p:lPersons){
            System.out.println(p.toString());
        }
    }
}
·
·二、android使用GSON
·ØGson这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。
·ØGson支持任意复杂Java对象包括没有源代码的对象。
·解析GSON格式如下例子代码:
·1.首先定义Person类,如上述
·2.创建GsonTools.java
package com.android.mygson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.android.domain.Person;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTools {
    public GsonTools() {}
    public static String createGsonString(Object object) {
        Gson gson = new Gson();
        String gsonString = gson.toJson(object);
        return gsonString;
    }
    public static <T> T changeGsonToBean(String gsonString, Class<T> cls) {
        Gson gson = new Gson();
        T t = gson.fromJson(gsonString, cls);
        return t;
    }
    public static <T> List<T> changeGsonToList(String gsonString, Class<T> cls) {
        Gson gson = new Gson();
        List<T> list_person = gson.fromJson(gsonString,
                new TypeToken<List<T>>() {
                }.getType());
        return list_person;
    }
    public static List<Map<String, Object>> changeGsonToListMaps(String gsonString) {
        List<Map<String, Object>> list = null;
        Gson gson = new Gson();
        list = gson.fromJson(gsonString,
                new TypeToken<List<Map<String, Object>>>() {
                }.getType());
        return list;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Person person1 = new Person("张三1", 24, "北京1");
        // Person person2 = new Person("张三2", 23, "北京2");
        // List<Person> list = new ArrayList<Person>();
        // list.add(person1);
        // list.add(person2);
        //
        // String gsonString = createGsonString(list);
        // System.out.println(gsonString);
        // Gson gson = new Gson();
        // List<Person> list_person = changeGsonToList(gsonString,Person.class);
        // System.out.println(list_person.toString());
        // Person pp = changeGsonToBean(gsonString,Person.class);
        // System.out.println(pp);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "jack");
        map.put("age", 23);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", "rose");
        map2.put("age", 24);
        list.add(map);
        list.add(map2);
        String gsonString = createGsonString(list);
        System.out.println(gsonString);
        List<Map<String, Object>> list2 = changeGsonToListMaps(gsonString);
        System.out.println(list2.toString());
    }
}
·
·三、android使用阿里巴巴fastjson技术
·ØFastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征
·Ø速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parser。包括自称最快的JackJson
·Ø功能强大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省。
·Ø无依赖,能够直接运行在Java SE 5.0以上版本
·Ø支持Android
·Ø开源 (Apache 2.0)
·解析GSON格式如下例子代码:
·1.首先定义Person类,如上述
·2.创建FastJsonTools.java
package com.android.myfastjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.asm.Type;
import com.alibaba.fastjson.util.TypeUtils;
public class FastJsonTools {
    public FastJsonTools() {}
    public static String createJsonString(Object object) {
        String jsonString = JSON.toJSONString(object);
        return jsonString;
    }
    public static <T> T createJsonBean(String jsonString, Class<T> cls) {
        T t = JSON.parseObject(jsonString, cls);
        return t;
    }
    public static <T> List<T> createJsonToListBean(String jsonString,
            Class<T> cls) {
        List<T> list = null;
        list = JSON.parseArray(jsonString, cls);
        return list;
    }
    public static List<Map<String, Object>> createJsonToListMap(
            String jsonString) {
        List<Map<String, Object>> list2 = JSON.parseObject(jsonString,
                new TypeReference<List<Map<String, Object>>>() {
                });
        return list2;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // Person person1 = new Person("张三1", 24, "北京1");
        // Person person2 = new Person("张三2", 23, "北京2");
        // List<Person> list = new ArrayList<Person>();
        // list.add(person1);
        // list.add(person2);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "jack");
        map.put("age", 23);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", "rose");
        map2.put("age", 24);
        list.add(map);
        list.add(map2);
        String jsonString = JSON.toJSONString(list);
        System.out.println(jsonString);
        // JSON.parseArray(arg0, arg1)
        List<Map<String, Object>> list2 = JSON.parseObject(jsonString,
                new TypeReference<List<Map<String, Object>>>() {
                });
        // List<Person> lists = JSON.parseArray(arg0, arg1);
        System.out.println(list2.toString());
    }
}
·
·四、JDBC框架介绍
·JDBC程序访问数据库的步骤 
·Ø步骤一:加载JDBC驱动程序
·Ø步骤二:提供连接参数
·Ø步骤三:建立一个数据库的连接
·Ø步骤四:创建一个statement
·Ø步骤五:执行SQL语句
·Ø步骤六:处理结果
·Ø步骤七:关闭JDBC对象
·
·JDBC代码范例
·1.定义基类:UserInfo.java
package com.jdbc.dbutils.domain;
import java.io.Serializable;
public class UserInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private String username;
    private String pswd;
    @Override
    public String toString() {
        return "UserInfo [id=" + id + ", username=" + username + ", pswd="
                + pswd + "]";
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPswd() {
        return pswd;
    }
    public void setPswd(String pswd) {
        this.pswd = pswd;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
    public UserInfo() {
        // TODO Auto-generated constructor stub
    }
}
·2.建立JdbcUtils.java类
package com.jdbc.dbutils;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jdbc.dbutils.domain.UserInfo;
public class JdbcUtils {
    // 表示定义数据库的用户名
    private final String USERNAME = "root";
    // 定义数据库的密码
    private final String PASSWORD = "admin";
    // 定义数据库的驱动信息
    private final String DRIVER = "com.mysql.jdbc.Driver";
    // 定义访问数据库的地址
    private final String URL = "jdbc:mysql://localhost:3306/mydb";
    // 定义数据库的链接
    private Connection connection;
    // 定义sql语句的执行对象
    private PreparedStatement pstmt;
    // 定义查询返回的结果集合
    private ResultSet resultSet;
    public JdbcUtils() {
        try {
            Class.forName(DRIVER);
            System.out.println("注册驱动成功!!");
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    // 定义获得数据库的链接
    public Connection getConnection() {
        try {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return connection;
    }
    /**
     * 完成对数据库的表的添加删除和修改的操作
     * 
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public boolean updateByPreparedStatement(String sql, List<Object> params)
            throws SQLException {
        boolean flag = false;
        int result = -1;// 表示当用户执行添加删除和修改的时候所影响数据库的行数
        pstmt = connection.prepareStatement(sql);
        int index = 1;
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        result = pstmt.executeUpdate();
        flag = result > 0 ? true : false;
        return flag;
    }
    /**
     * 查询返回单条记录
     * 
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public Map<String, Object> findSimpleResult(String sql, List<Object> params)
            throws SQLException {
        Map<String, Object> map = new HashMap<String, Object>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();// 返回查询结果
        ResultSetMetaData metaData = resultSet.getMetaData();
        int col_len = metaData.getColumnCount();// 获得列的名称
        while (resultSet.next()) {
            for (int i = 0; i < col_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
        }
        return map;
    }
    /**
     * 查询返回多行记录
     * 
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public List<Map<String, Object>> findMoreResult(String sql,
            List<Object> params) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                map.put(cols_name, cols_value);
            }
            list.add(map);
        }
        return list;
    }
    // jdbc的封装可以用反射机制来封装:
    public <T> T findSimpleRefResult(String sql, List<Object> params,
            Class<T> cls) throws Exception {
        T resultObject = null;
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            // 通过反射机制创建实例
            resultObject = cls.newInstance();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                Field field = cls.getDeclaredField(cols_name);
                field.setAccessible(true);// 打开javabean的访问private权限
                field.set(resultObject, cols_value);
            }
        }
        return resultObject;
    }
    /**
     * 通过反射机制访问数据库
     * 
     * @param <T>
     * @param sql
     * @param params
     * @param cls
     * @return
     * @throws Exception
     */
    public <T> List<T> findMoreRefResult(String sql, List<Object> params,
            Class<T> cls) throws Exception {
        List<T> list = new ArrayList<T>();
        int index = 1;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int cols_len = metaData.getColumnCount();
        while (resultSet.next()) {
            T resultObject = cls.newInstance();
            for (int i = 0; i < cols_len; i++) {
                String cols_name = metaData.getColumnName(i + 1);
                Object cols_value = resultSet.getObject(cols_name);
                if (cols_value == null) {
                    cols_value = "";
                }
                Field field = cls.getDeclaredField(cols_name);
                field.setAccessible(true);
                field.set(resultObject, cols_value);
            }
            list.add(resultObject);
        }
        return list;
    }
    public void releaseConn() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JdbcUtils jdbcUtils = new JdbcUtils();
        jdbcUtils.getConnection();
        // String sql = "insert into userinfo(username,pswd) values(?,?)";
        // List<Object> params = new ArrayList<Object>();
        // params.add("rose");
        // params.add("123");
        // try {
        // boolean flag = jdbcUtils.updateByPreparedStatement(sql, params);
        // System.out.println(flag);
        // } catch (SQLException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
        String sql = "select * from userinfo ";
//      List<Object> params = new ArrayList<Object>();
//      params.add(1);
        try {
            List<UserInfo> list = jdbcUtils.findMoreRefResult(sql,
                    null, UserInfo.class);
            System.out.println(list);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            jdbcUtils.releaseConn();
        }
    }
}
·
·
·
·
·
·
·Over

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试