1、首先,搭建一个服务器的工程:JsonProject这个项目
源代码:
Person.java
package com.json.domain
public class Person {
private int id
private String name
private String address
public Person() {
super()
}
public Person(int id, String name, String addrss) {
super()
this.id = id
this.name = name
this.address = addrss
}
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 getAddress() {
return address
}
public void setAddress(String address) {
this.address = address
}
@Override
public String toString() {
return "Person [addrss=" + address + ", id=" + id + ", name=" + name
+ "]"
}
}
JsonService.java
package com.json.service
import java.util.ArrayList
import java.util.HashMap
import java.util.List
import java.util.Map
import com.json.domain.Person
public class JsonService {
public JsonService() {
}
public Person getPerson(){
Person person = new Person(1001,"jack","上海黄浦区")
return person
}
public List<Person>getListPerson(){
List<Person>list = new ArrayList<Person>()
Person person1 = new Person(1001,"jack","上海黄浦区")
Person person2 = new Person(1002,"rose","上海闵行区")
Person person3 = new Person(1003,"mick","上海黄浦区")
list.add(person1)
list.add(person2)
list.add(person3)
return list
}
public List<String>getListString(){
List<String>list = new ArrayList<String>()
list.add("北京")
list.add("上海")
list.add("湖南")
return list
}
public List<Map<String,Object>>getListMaps(){
List<Map<String,Object>>list = new ArrayList<Map<String,Object>>()
Map<String,Object>map1 = new HashMap<String, Object>()
Map<String,Object>map2 = new HashMap<String, Object>()
map1.put("id", 1001)
map1.put("name", "jack")
map1.put("address", "北京")
map2.put("id", 1001)
map2.put("name", "rose")
map2.put("address", "上海")
list.add(map1)
list.add(map2)
return list
}
}
JsonServlet.java
package com.json.servlet
import java.io.IOException
import java.io.PrintWriter
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import com.json.service.JsonService
import com.json.tools.JsonTools
public class JsonServlet extends HttpServlet {
private JsonService service
/**
* Constructor of the object.
*/
public JsonServlet() {
super()
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy()// Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response)
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/htmlcharset=utf-8")
request.setCharacterEncoding("utf-8")
response.setCharacterEncoding("utf-8")
PrintWriter out = response.getWriter()
String jsonString = ""
String action_flag = request.getParameter("action_flag")
if(action_flag.equals("person")){
jsonString = JsonTools.createJsonString("person", service.getPerson())
}else if(action_flag.equals("persons")){
jsonString = JsonTools.createJsonString("persons", service.getListPerson())
}else if(action_flag.equals("listString")){
jsonString = JsonTools.createJsonString("listString", service.getListString())
}else if(action_flag.equals("listMap")){
jsonString = JsonTools.createJsonString("listMap", service.getListMaps())
}
out.println(jsonString)
out.flush()
out.close()
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
service = new JsonService()
}
}
2、通过浏览器
访问地址一:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=person
输出以下结果:
{"person":{"address":"上海黄浦区","id":1001,"name":"jack"}
访问地址二:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=persons
输出以下结果:
{"persons":[{"address":"上海黄浦区","id":1001,"name":"jack"},{"addrss":"上海闵行区","id":1002,"name":"rose"},{"address":"上海黄浦区","id":1003,"name":"mick"}]}
访问地址三:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=listString
输出以下结果:
{"persons":["北京","上海","湖南"]}
访问地址四:http://wulianghuan-pc:8080/JsonProject/servlet/JsonServlet?action_flag=listMap
输出以下结果:
{"persons":[{"id":1001,"address":"北京","name":"jack"},{"id":1001,"address":"上海","name":"rose"}]}
因为这次要从服务器端得到Json数据,并且通过解析之后把解析后的数据显示在Android客户端中,首先部署服务器端代码(直接使用Jsp/Servlet):构造的Json数据如下:
[{"name":"张三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]
[一]服务器端(Person.java省略):
①:数据构造JsonService.java
public class JsonService {
public static List<Person>getListPerson() {
List<Person>mLists = new ArrayList<Person>()
mLists.add(new Person("张三", "北京", 20))
mLists.add(new Person("李四", "上海", 30))
mLists.add(new Person("王五", "深圳", 35))
return mLists
}
②:Servlet的代码(包括构造Json数据,没有使用Json数据转换方法)JsonServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html")
response.setCharacterEncoding("UTF-8")
PrintWriter out = response.getWriter()
List<Person>persons = JsonService.getListPerson()
StringBuffer sb = new StringBuffer()
sb.append('[')
for (Person person : persons) {
sb.append('{').append("\"name\":").append("\""+person.getName()+"\"").append(",") sb.append("\"address\":").append("\""+person.getAddress()+"\"").append(",")
sb.append("\"age\":").append(person.getAge())
sb.append('}').append(",")
}
sb.deleteCharAt(sb.length() - 1)
sb.append(']')
out.write(new String(sb))
out.flush()
out.close()
}
③:部署到Tomact 浏览器输入http://localhost/JsonWeb/JsonServlet直接访问结果如下:
[{"name":"张三","address":"北京","age":20},{"name":"李四","address":"上海","age":30},{"name":"王五","address":"深圳","age":35}]
至此服务器端代码编码完成,下面进行客户端代码编写 (二)客户端(Person类,和展示数据的布局文件因为简单省去) ①:获取服务器端的Json数据并且解析的工具类JsonParse.java 必要的需要导入的包省去
public class JsonParse {
/**
* 解析Json数据
*
* @param urlPath
* @return mlists
* @throws Exception
*/
public static List<Person>getListPerson(String urlPath) throws Exception {
List<Person>mlists = new ArrayList<Person>()
byte[] data = readParse(urlPath)
JSONArray array = new JSONArray(new String(data))
for (int i = 0i <array.length()i++) {
JSONObject item = array.getJSONObject(i)
String name = item.getString("name")
String address = item.getString("address")
int age = item.getInt("age")
mlists.add(new Person(name, address, age))
}
return mlists
}
/**
* 从指定的url中获取字节数组
*
* @param urlPath
* @return 字节数组
* @throws Exception
*/
public static byte[] readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream()
byte[] data = new byte[1024]
int len = 0
URL url = new URL(urlPath)
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
InputStream inStream = conn.getInputStream()
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len)
}
inStream.close()
return outStream.toByteArray()
}
}
②:主Activity类
public class MainActivity extends Activity {
private Button mButton
private ListView mListView
//使用IP不能使用localhost或者127.0.0.1,因为android模拟器默认绑定这个IP,这里应该访问局域网IP
private static final String urlPath = "http://10.16.31.207/JsonWeb/JsonServlet"
private static final String TAG = "MainActivity"
private List<Person>persons
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
mButton = (Button) findViewById(R.id.button1)
mListView = (ListView) findViewById(R.id.listView1)
mButton.setOnClickListener(new MyOnClickListener())
}
private class MyOnClickListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
// 得到Json解析成功之后数据
persons = JsonParse.getListPerson(urlPath)
List<HashMap<String, Object>>data = new ArrayList<HashMap<String, Object>>()
for (int i = 0i <persons.size()i++) {
HashMap<String, Object>map = new HashMap<String, Object>()
map.put("name", persons.get(i).getName())
map.put("address", persons.get(i).getAddress())
map.put("age", persons.get(i).getAge())
data.add(map)
}
//初始化适配器,并且绑定数据
SimpleAdapter _Adapter = new SimpleAdapter(MainActivity.this,
data, R.layout.listview_item, new String[] { "name",
"address", "age" }, new int[] { R.id.textView1,
R.id.textView2, R.id.textView3 })
mListView.setAdapter(_Adapter)
} catch (Exception e) {
Toast.makeText(MainActivity.this, "解析失败", 2000).show()
Log.i(TAG, e.toString())
}
}
}
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)