第一步要有一个服务端我用是struts2返回jsone格式的,之前struts2如何搭建这里就不记录了
在服务端的action类将获得的数据转换为jsone
public class QuestionAction {
.。。。。。。
private Map infoMap=new HashMap();
public Map getInfoMap() {
return infoMap;
}
public void setInfoMap(Map infoMap) {
this.infoMap = infoMap;
}
public int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String findQuestions(){
System.out.println("id: "+id);
List<QuestionsForm> list = questionsDAO.query(id);
if(list!=null){
System.out.println("total: "+list.size());
QuestionsForm q = (QuestionsForm) list.get(0);
//把list转换为jsone
net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(list);
infoMap.put("returnData", array);
}else{
System.out.println("error ");
}
return "success";
}
}
第二步验证是否有值返回我用的是google,ie的话是弹出一个文件不喜欢
http://10.7.3.118:8888/exam_tang/questionsAction!findQuestions.action?id=1
返回值是:
{"id":1,"infoMap":{"returnData":[{"optionD":"以上都不是","optionC":"应用程序","optionB":"操作系统","lessonId":1,"optionA":"应用软件","taoTiId":1,"subject":"Windows 2000是什么?","ID":1,"answer":"B","type":"单选题","note":"空"}]}}写这里的时候有个小插曲,尽量不要吧数据类型搞得太复杂 最好是string或者int的两种
第三步客户端访问服务端地址
在访问url之前要写一个工具类JSONUtil和引入7个包commons-beanutils.jar commons-collections-3.1.jar commons-lang.jar commons-lang3-3.1.jar commons-logging-1.0.4.jar ezmorph-1.0.6.jar json-lib-2.2.3-jdk15.jar 为了jsone解析用
package com;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
/**
* Json封装的工具类.
*/
public class JSONUtil {
private static final String TAG = "JSONUtil";
/**
* 获取json内容
* @param url
* @return JSONArray
* @throws JSONException
* @throws ConnectionException
*/
public static JSONObject getJSON(String url) throws JSONException, Exception {
return new JSONObject(getRequest(url));
}
/**
* 向api发送get请求,返回从后台取得的信息。
*
* @param url
* @return String
*/
protected static String getRequest(String url) throws Exception {
return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
}
/**
* 向api发送get请求,返回从后台取得的信息。
*
* @param url
* @param client
* @return String
*/
protected static String getRequest(String url, DefaultHttpClient client) throws Exception {
String result = null;
int statusCode = 0;
HttpGet getMethod = new HttpGet(url);
Log.d(TAG, "do the getRequest,url="+url+"");
try {
//getMethod.setHeader("User-Agent", USER_AGENT);
HttpResponse httpResponse = client.execute(getMethod);
//statusCode == 200 正常
statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("----------"+statusCode);
Log.d(TAG, "statuscode = "+statusCode);
//处理返回的httpResponse信息
result = retrieveInputStream(httpResponse.getEntity());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
throw new Exception(e);
} finally {
getMethod.abort();
}
return result;
}
/**
* 处理httpResponse信息,返回String
*
* @param httpEntity
* @return String
*/
protected static String retrieveInputStream(HttpEntity httpEntity) {
int length = (int) httpEntity.getContentLength();
//the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.
//length==-1,下面这句报错,println needs a message
if (length < 0) length = 10000;
StringBuffer stringBuffer = new StringBuffer(length);
try {
InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
char buffer[] = new char[length];
int count;
while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
stringBuffer.append(buffer, 0, count);
}
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
return stringBuffer.toString();
}
}
第四步 解析获得数据存放在bean类里,在Activity类里使用
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testsetupViews();
}
public void testsetupViews(){
//获取后台返回的Json对象
try {
JSONObject mJsonObject = JSONUtil.getJSON(testBASE_URL);
JSONObject a = (JSONObject) mJsonObject.get("infoMap");
JSONArray arr=a.getJSONArray("returnData");
int size = arr.length();
if(size>0){
JSONObject ww = arr.getJSONObject(0);
question.setOptionA(ww.getString("optionA"));
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
好这样就完成了!
jsone用的jar包
引入7个包commons-beanutils.jar
commons-collections-3.1.jar
commons-lang.jar
commons-lang3-3.1.jar
commons-logging-1.0.4.jar
ezmorph-1.0.6.jar
json-lib-2.2.3-jdk15.jar
不知道怎么上传到这里来,不会使用啊,有用的时候自己下载吧!!!!