Android - 使用Gson输出数据,使android可解析

目录

1.首先是数据库的准备,用MySQL存储数据。

2.然后在服务端查询出数据,输出JSON格式数据。

创建数据库

CREATE database MyNews;
use MyNews;
CREATE TABLE newtable (
    id INT PRIMARY KEY AUTO_INCREMENT,
    title TEXT NOT NULL,
    descs TEXT NOT NULL,
    times TIMESTAMP DEFAULT CURRENT_TIMESTAMP (),
    pic_url TEXT,
    content_url TEXT
);

然后插入一些数据。

导入jar包

需要导入gson(操作json)和jdbc(连接数据库)的jar包,这里大家自行下载吧。

如果你用的是Eclipse,那么将jar包放入WEB_INF下的lib文件夹下,右击复制进去的jar包,选择Build Path >> Add to Build Path。

Java编码

index.jsp

这里举例就这样写了。

<%@page import="com.google.gson.JsonArray"%>
<%@page import="com.google.gson.JsonObject"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        String sql = "SELECT * FROM newtable";
        // 数据库链接
        Connection conn = null;
        // 向数据库发送sql语句
        Statement st = null;
        // 结果集
        ResultSet rs = null;
        String url = "jdbc:mysql://localhost:3306/MyNews";
        String user = "root";
        String pass = "wuxc";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //数据库的地址,密码,用户名
            conn = DriverManager.getConnection(url, user, pass);
            st = conn.createStatement();
            rs = st.executeQuery(sql);

            JsonObject object = new JsonObject();
            JsonArray array = new JsonArray();

            while (rs.next()) {

                JsonObject ob = new JsonObject();

                ob.addProperty("id", rs.getInt("id"));
                ob.addProperty("title", rs.getString("title"));
                ob.addProperty("descs", rs.getString("descs"));
                ob.addProperty("times", rs.getString("times"));
                ob.addProperty("pic_url", rs.getString("pic_url"));
                ob.addProperty("content_url", rs.getString("content_url"));

                array.add(ob);
            }

            object.add("News", array);
            out.print(object.toString());

        } catch (Exception e) {

        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
            try {
                st.close();
            } catch (Exception e) {
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    %>
</body>
</html>

输出结果

{  
    "News": [  
        {  
            "id": 1,  
            "title": "Java基础之静态static",  
            "descs": "static是一个成员修饰符,定义功能时,如果功能不需要访问类中定义的非静态成员变量时,该功能就需要静态修饰",  
            "times": "2016-04-26 23:43:01.0",  
            "pic_url": null,  
            "content_url": "/wu_wxc/article/details/49539247"  
        },  
        {  
            "id": 2,  
            "title": "Android二维码",  
            "descs": "在Android中扫描和生成二维码,可以用网上的一个开源库",  
            "times": "2016-04-26 23:44:12.0",  
            "pic_url": "20160414221340274",  
            "content_url": "/wu_wxc/article/details/51153142"  
        },  
        {  
            "id": 4,  
            "title": "Android日志Log",  
            "descs": "日志可以在帮我们开发中调试程序,下面看看Android自带日志的作用",  
            "times": "2016-04-26 23:46:50.0",  
            "pic_url": "20160417230459394",  
            "content_url": "/wu_wxc/article/details/51175977"  
        }  
    ]  
}  

让Android可解析

如果要在Android上解析的话,这时会出现

org.json.JSONException: Value <!DOCTYPE of type Java.lang.String cannot be converted to JSONArray

在AS里打印内容有

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <html>  <head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  <title>Insert title here</title>  </head>  <body>

直接把jsp文件里html的内容去掉就行
下面把Jsp打印JSON数据重新整理一下
代码如下:

index.jsp

<%@page import="com.google.gson.JsonArray"%>  
<%@page import="com.google.gson.JsonObject"%>  
<%@page import="java.sql.DriverManager"%>  
<%@page import="java.sql.ResultSet"%>  
<%@page import="java.sql.Statement"%>  
<%@page import="java.sql.Connection"%>  
<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  

<%  
    String sql = "SELECT * FROM newtable";  
    // 数据库链接  
    Connection conn = null;  
    // 向数据库发送sql语句  
    Statement st = null;  
    // 结果集  
    ResultSet rs = null;  
    String url = "jdbc:mysql://localhost:3306/MyNews";  
    String user = "root";  
    String pass = "wuxc";  
    try {  
        Class.forName("com.mysql.jdbc.Driver");  
        //数据库的地址,密码,用户名  
        conn = DriverManager.getConnection(url, user, pass);  
        st = conn.createStatement();  
        rs = st.executeQuery(sql);  

        JsonArray array = new JsonArray();  

        while (rs.next()) {  

            JsonObject ob = new JsonObject();  

            ob.addProperty("id", rs.getInt("id"));  
            ob.addProperty("title", rs.getString("title"));  
            ob.addProperty("descs", rs.getString("descs"));  
            ob.addProperty("times", rs.getString("times"));  
            ob.addProperty("pic_url", rs.getString("pic_url"));  
            ob.addProperty("content_url", rs.getString("content_url"));  

            array.add(ob);  
        }  

        out.print(array);  

    } catch (Exception e) {  

    } finally {  
        try {  
            rs.close();  
        } catch (Exception e) {  
        }  
        try {  
            st.close();  
        } catch (Exception e) {  
        }  
        try {  
            conn.close();  
        } catch (Exception e) {  
        }  
    }  
%>  

将JSON数据重新格式化

[  
    {  
        "id": 1,  
        "title": "Java基础之静态static",  
        "descs": "static是一个成员修饰符,定义功能时,如果功能不需要访问类中定义的非静态成员变量时,该功能就需要静态修饰",  
        "times": "2016-04-26 23:43:01.0",  
        "pic_url": null,  
        "content_url": "/wu_wxc/article/details/49539247"  
    },  
    {  
        "id": 2,  
        "title": "Android二维码",  
        "descs": "在Android中扫描和生成二维码,可以用网上的一个开源库",  
        "times": "2016-04-26 23:44:12.0",  
        "pic_url": "20160414221340274",  
        "content_url": "/wu_wxc/article/details/51153142"  
    },  
    {  
        "id": 4,  
        "title": "Android日志Log",  
        "descs": "日志可以在帮我们开发中调试程序,下面看看Android自带日志的作用",  
        "times": "2016-04-26 23:46:50.0",  
        "pic_url": "20160417230459394",  
        "content_url": "/wu_wxc/article/details/51175977"  
    }  
]  

现在再在Android上解析就没问题了!!!

还有这篇文章大家可以看一下:

Android网络之数据解析----使用Google Gson解析Json数据

Android中使用Gson解析JSON数据

文章最后编辑时间为:2017-02-14 13:26:45

标签: java android gson

声明:本博客如无特殊说明皆为原创,转载请注明来源:Android - 使用Gson输出数据,使android可解析谢谢!

相关文章

发表评论:

icon_question.pngicon_razz.pngicon_sad.pngicon_evil.pngicon_exclaim.pngicon_smile.pngicon_redface.pngicon_biggrin.pngicon_surprised.pngicon_eek.pngicon_confused.pngicon_cool.pngicon_lol.pngicon_mad.pngicon_twisted.pngicon_rolleyes.pngicon_wink.pngicon_idea.pngicon_arrow.pngicon_neutral.pngicon_cry.pngicon_mrgreen.png