Android与Java服务器端数据交互和Java对象转换成JSON对象

时间:2022-12-02 09:55:03

用Java写Android的后端与Android进行交互,本文后台是采用Struts2框架,使用Http协议获取服务器端数据,写一个查询
Java JSON jar包:http://download.csdn.net/download/liu_c_y/9543241
完整的代码http://download.csdn.net/detail/liu_c_y/9559472

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>

项目部署后,在浏览器中可以看到测试结果
Android与Java服务器端数据交互和Java对象转换成JSON对象

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;
}


}

个人博客:http://www.javaknowledge.cn/?p=42