Android與Java伺服器端資料互動和Java物件轉換成JSON物件
阿新 • • 發佈:2019-01-01
Ticket封裝成一個類
package com.model;
public class Ticket {
private int ticket_id;
private int price;
private int user_id;
private int sit_num;
private String from_sp;
private String to_sp;
private String time_leave;
private String time_arrive;
private String date;
public int getTicket_id() {
return ticket_id;
}
public void setTicket_id(int ticket_id) {
this.ticket_id = ticket_id;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getSit_num() {
return sit_num;
}
public void setSit_num(int sit_num) {
this.sit_num = sit_num;
}
public String getFrom_sp() {
return from_sp;
}
public void setFrom_sp(String from_sp) {
this.from_sp = from_sp;
}
public String getTo_sp() {
return to_sp;
}
public void setTo_sp(String to_sp) {
this.to_sp = to_sp;
}
public String getTime_leave() {
return time_leave;
}
public void setTime_leave(String time_leave) {
this.time_leave = time_leave;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime_arrive() {
return time_arrive;
}
public void setTime_arrive(String time_arrive) {
this.time_arrive = time_arrive;
}
}
資料庫連線程式碼
package com.conn;
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
public class Conn {
private String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
private String user = "root";
private String pass = "";
public Connection getConn(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(url, user, pass);
return conn;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
編寫TicketDAO類
package com.conn;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class TicketDAO {
private Connection conn;
private PreparedStatement pstmt;
private ArrayList<com.model.Ticket> list = new ArrayList<com.model.Ticket>();
public TicketDAO(){
conn = new Conn().getConn();
}
public ArrayList<com.model.Ticket> findTicket(int user_id){
try {
pstmt = conn.prepareStatement("select * from buy_ticket where user_id=?");
pstmt.setInt(1,user_id);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
com.model.Ticket ticket = new com.model.Ticket();
ticket.setDate(rs.getString("date"));
ticket.setSit_num(rs.getInt("sit_num"));
ticket.setUser_id(rs.getInt("user_id"));
ticket.setPrice(rs.getInt("price"));
ticket.setTime_leave(rs.getString("time_leave"));
ticket.setTime_arrive(rs.getString("time_arrive"));
ticket.setTo_sp(rs.getString("to_sp"));
ticket.setFrom_sp(rs.getString("from_sp"));
ticket.setTicket_id(rs.getInt("ticket_id"));
list.add(ticket);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public boolean addTicket(int user_id,int p_id){
try {
pstmt = conn.prepareStatement("insert into buy_ticket (from_sp,to_sp,time_arrive,time_leave,price,user_id,sit_num,date) "
+ "select from_sp,to_sp,time_arrive,time_leave,price,'"+user_id+"',car.number-price.rest+1,date from "
+ "price natural join time_table natural join car where price.p_id =?");
pstmt.setInt(1, p_id);
int rs = pstmt.executeUpdate();
if(rs>0){
pstmt = conn.prepareStatement("update price set rest = rest-1 where p_id = ?");
pstmt.setInt(1, p_id);
pstmt.executeUpdate();
return true;
}else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
Ticket Action類
這個類是關鍵,接收Android端的資料與接收web傳來的資料一樣,返回資料以JSON資料包返回。在Action類中需要呼叫ServletAPI來進行響應請求
package com.user.service;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONStringer;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.conn.TicketDAO;
import com.opensymphony.xwork2.ActionSupport;
public class Ticket extends ActionSupport implements ServletRequestAware,ServletResponseAware{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private int user_id;
private int p_id;
public void setServletRequest(HttpServletRequest request) {
this.setRequest(request);
}
public void setServletResponse(HttpServletResponse response) {
this.setResponse(response);
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public int getP_id() {
return p_id;
}
public void setP_id(int p_id) {
this.p_id = p_id;
}
public void findTicket(){
ArrayList<com.model.Ticket> list = new ArrayList<com.model.Ticket>();
TicketDAO ticketDAO = new TicketDAO();
list = ticketDAO.findTicket(getUser_id());
//將ArrayList物件轉換成JSON資料
JSONArray json = JSONArray.fromObject(list);
//防止中文亂碼
response.setContentType("text/html;charset=utf-8");
try {
//將後臺資料返回安卓端
this.response.getWriter().write(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void addTicket(){
TicketDAO ticketDAO = new TicketDAO();
boolean result = ticketDAO.addTicket(getUser_id(),getP_id());
response.setContentType("text/html;charset=utf-8");
JSONStringer stringer = new JSONStringer();
if(result){
String str = stringer.object().key("value").value(1).endObject().toString();
try {
this.response.getWriter().write(str);
} catch (IOException e) {
e.printStackTrace();
}
}else{
String str = stringer.object().key("value").value(0).endObject().toString();
try {
this.response.getWriter().write(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Struts.xml檔案的配置
package 必須繼承json-default
result 返回的型別為json
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="user" extends="json-default">
<action name="addUser" class="com.user.service.AddUser" method="add">
<result type="json"></result>
</action>
<action name="userLogin" class="com.user.service.AddUser" method="find">
<result type="json"></result>
</action>
<action name="findTimePrice" class="com.user.service.Timeprice" method="find">
<result type="json"></result>
</action>
<action name="findTicket" class="com.user.service.Ticket" method="findTicket">
<result type="json"></result>
</action>
<action name="addTicket" class="com.user.service.Ticket" method="addTicket">
<result type="json"></result>
</action>
</package>
</struts>
專案部署後,在瀏覽器中可以看到測試結果
Java物件轉換成JSON物件
主要有JSONArray JSONObject JSONStinger
package jsonDemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONStringer;
public class Demo1 {
private String name;
private int id;
private ArrayList<?> list;
public static void main(String [] args){
//普通型別、List、Collection等都是用JSONArray解析
//普通陣列
String[] list = new String[]{"one","two","three"};
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray.toString());//["one","two","three"]
//List
List<String> list1 = new ArrayList<String>();
list1.add("one");
list1.add("two");
list1.add("three");
JSONArray jsonArray1 = JSONArray.fromObject(list1);
System.out.println(jsonArray1.toString());//["one","two","three"]
//Map
Map<String, String> params = new HashMap<String, String>();
params.put("username", "lcy");
params.put("user_json", "scau");
JSONArray array = JSONArray.fromObject(params);
System.out.println(array.toString());//[{"username":"lcy","user_json":"scau"}]
JSONObject jsonObject = JSONObject.fromObject( params );
System.out.println(jsonObject.toString());//{"username":"lcy","user_json":"scau"}
//Map也可以理解成一個物件,也可以使用JSONObject來解析
//普通自定義型別,使用JSONObject
Demo1 demo1 = new Demo1();
demo1.setId(123);
demo1.setName("lcy");
demo1.setList(list1);
JSONObject jsonDemo1 = JSONObject.fromObject(demo1);
System.out.println(jsonDemo1.toString());//{"id":123,"list":["one","two","three"],"name":"lcy"}
//使用JSONStringer構造一個json資料
JSONStringer stringer = new JSONStringer();
String str = stringer.object().key("name").value("lcy").key("id").value(1).endObject().toString();//要使用enObject()作為結尾
System.out.println(str);//{"name":"lcy","id":1}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ArrayList<?> getList() {
return list;
}
public void setList(List<String> list1) {
this.list = (ArrayList<?>) list1;
}
}