Android学习--封装成json数据和解析json数据
程序员文章站
2024-01-14 19:33:28
...
参考博客:http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html(如果涉及版权问题,请联系我。)
JSON的全称是”JavaScript
Object Notation”,意思是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式。XML也是一种数据交换格式,为什么没有选择XML呢?因为XML虽然可以作为跨平台的数据交换格式,但是在JS(JavaScript的简写)中处理XML非常不方便,同时XML标记比数据多,增加了交换产生的流量,而JSON没有附加的任何标记,在JS中可作为对象处理,所以我们更倾向于选择JSON来交换数据。这篇文章主要从以下几个方面来说明JSON。
1.json数据认识
2.封装json数据
3.json解析
4.从客户端数据传输到服务器端
5.从服务器端下载数据到客户端
6.json应用
开发环境:win7,eclipse,服务器端 tomcat7.0,Android
一、json数据认识
JSON有两种表示结构,对象和数组。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。
[
{
key1: value1,
key2: value2
},
{
key3: value3,
key4: value4
}
]
{
key1: value1,
key2: value2
},
{
key3: value3,
key4: value4
}
]
实例:
{
"data": {
"info": [
{
"bmi": "0",
"contents": "22233",
"time": "2015-05-14",
"title": "2"
},
{
"bmi": "0",
"contents": "new",
"time": "2015-05-14",
"title": "33"
}
]
},
"ret": 0,
"msg": "ok"
}
二、封装json数据
private void jsonForm1() {
// TODO Auto-generated method stub
try {
JSONObject person=new JSONObject();
JSONArray phone=new JSONArray();
phone.put("12345678").put("87654321");
person.put("phone", phone);
person.put("name", "zhangsanfeng");
person.put("age", 20);
JSONObject address=new JSONObject();
address.put("country", "China");
address.put("province", "zhejiang");
person.put("address", address);
person.put("married", false);
Log.d(TAG, "person:"+person.toString());
Log.d(TAG, person.getString("name"));
} catch (JSONException ex) {
// TODO: handle exception
throw new RuntimeException(ex);
}
}
二、json解析
private static final String JSON = "{"
+ "\"phone\" : [\"12345678\", \"87654321\"],"
+ " \"name\" : \"yuanzhifei89\","
+ " \"age\" : 100,"
+ " \"address\" : { \"country\" : \"china\", \"province\" : \"jiangsu\" },"
+ " \"married\" : false" + "}";
private void jsonParse(){
try {
JSONObject person=new JSONObject(JSON);
Log.d(TAG, person.toString());
person.getJSONArray("phone");
Log.d(TAG, "person name"+person.getString("name"));
Log.d(TAG, "person age"+person.getInt("age"));
Log.d(TAG, "person marride"+person.getBoolean("marride"));
JSONArray myArray=person.getJSONArray("phone");
Log.d(TAG, "person phone"+myArray.toString());
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
三、 从客户端数据传输到服务器端
客户端代码:
package com.example.asyntaskdome;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class AddUserAsyncTask extends AsyncTask<String, Void, String> {
TextView textRes;
protected String doInBackground(String...params){
HttpPost request=new HttpPost(params[0]);
JSONObject param=new JSONObject();
try {
Log.d("sqt", "post......");
param.put("username", "sqt");
param.put("userpassword", "123456");
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
StringEntity se;
try {//向服务器端发送数据
se=new StringEntity(param.toString());
request.setEntity(se);
HttpResponse httpResponse=new DefaultHttpClient().execute(request);
String retSrc=EntityUtils.toString(httpResponse.getEntity());
Log.d("sqt", "retSrc:"+retSrc);
return JsonParser(retSrc);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
//根据从服务器返回回来的数据,进行解析,判断是否传输成功
private String JsonParser(String retSrc) {
// TODO Auto-generated method stub
String result=null;
try {
JSONObject ret=new JSONObject(retSrc);
int rr=ret.getInt("ret");
if (rr==1) {
result="success";
}else {
result="error";
}
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
}
服务器端代码:
package com.sqt.web.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sqt.web.dao.UserDao;
import com.sqt.web.model.User;
public class AddUsersServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
JSONObject jObject=new JSONObject();
String addUserString=converStreamToString(req.getInputStream());
HashMap<String, String>user=JsonParser(addUserString);
try {
UserDao uDao=new UserDao();
if (uDao.insert(user.get("username"), user.get("password"))) {
try {
jObject.put("ret", 1);
jObject.put("msg", "ok");
jObject.put("data", "");
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}else {
jObject.put("ret", 99);
jObject.put("msg", "cannot insert record");
jObject.put("data", "");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
PrintWriter out=resp.getWriter();
out.print(jObject);
out.flush();
out.close();
}
//通过http传递的流数据,转化成string类型
private String converStreamToString(InputStream is){
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuilder sb=new StringBuilder();
String line=null;
try {
while ((line=reader.readLine())!=null) {
sb.append(line+"/n");
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
return sb.toString();
}
//对json数据进行解析
private HashMap<String, String> JsonParser(String jsonString) {
HashMap<String, String> hashMap = new HashMap<String, String>();
try {
JSONObject jsObject=new JSONObject(jsonString);
hashMap.put("username",jsObject.getString("username"));
hashMap.put("password",jsObject.getString("userpassword"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return hashMap;
}
}
四、从服务器端下载数据到客户端
服务器端代码:
package com.sqt.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sqt.web.dao.UserDao;
import com.sqt.web.model.User;
public class GetUsersServlet extends HttpServlet {
private static final long serialVersionUID=-6534417657358062448L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
JSONObject jObject=new JSONObject();
UserDao userDao;
try {
userDao=new UserDao();
ArrayList<User>retList=userDao.getUsers();
JSONObject jObject2=new JSONObject();
jObject2.put("totalnum", retList.size());
JSONArray userlist=new JSONArray();
for (User user:retList) {
JSONObject record=new JSONObject();
record.put("_id", user.getUid());
record.put("username", user.getUsername());
record.put("userpassword", user.getPassword());
userlist.put(record);
}
jObject2.put("info", userlist);
jObject.put("ret", 0);
jObject.put("msg", "ok");
jObject.put("data", jObject2);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
try {
jObject.put("ret", 1);
jObject.put("msg", e.getMessage());
jObject.put("data", "");
} catch (JSONException ex) {
// TODO: handle exception
ex.printStackTrace();
}
}
PrintWriter out=response.getWriter();
out.print(jObject);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
客户端端代码:
package com.example.asyntaskdome;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.R.mipmap;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class HttpAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, Object>>> {
private ListView listView;
private Context context;
public HttpAsyncTask(Context context, ListView listView) {
this.context = context;
this.listView = listView;
}
@Override
protected ArrayList<HashMap<String, Object>> doInBackground(
String... params) {
// TODO Auto-generated method stub
String responseStr = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
responseStr = EntityUtils.toString(httpResponse.getEntity());
} else {
responseStr = "返回值" + statusCode;
}
} catch (Exception e) {
// TODO: handle exception
Log.d("sqt", e.getMessage());
}
if (responseStr != null) {
return jsonParse(responseStr);
}
return null;
}
@Override
protected void onPostExecute(ArrayList<HashMap<String, Object>> result) {
// TODO Auto-generated method stub
Log.d("sqt", "post");
if (result == null) {
Log.d("sqt", "sqt null");
}
Log.d("sqt", "result" + result.size());
listView.setAdapter(new SimpleAdapter(context, result, R.layout.vlist,
new String[] { "uid", "username", "password" }, new int[] {
R.id.id, R.id.username, R.id.password }));
// super.onPostExecute(result);
}
private ArrayList<HashMap<String, Object>> jsonParse(String jsonString) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
int retCode = jsonObject.getInt("ret");
Log.d("sqt", "retCode" + retCode);
if (0 == retCode) {
JSONObject dataObject = jsonObject.getJSONObject("data");
int totalnum = dataObject.getInt("totalnum");
Log.d("sqt", "totalnum" + totalnum);
if (totalnum > 0) {
JSONArray userlist = dataObject.getJSONArray("info");
Log.d("sqt", "totalnum" + userlist.length());
for (int i = 0; i < userlist.length(); i++) {
JSONObject userObject = (JSONObject) userlist.opt(i);
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("uid",
Integer.valueOf(userObject.getInt("_id")));
hashMap.put("username",userObject.getString("username"));
hashMap.put("password",userObject.getString("userpassword"));
resultList.add(hashMap);
Log.d("sqt","uid"+ Integer.valueOf(userObject.getInt("_id")));
Log.d("sqt","username" + userObject.getString("username"));
Log.d("sqt","password"+ userObject.getString("userpassword"));
Log.d("sqt", "add suceess");
}
return resultList;
}
}
} catch (Exception e) {
// TODO: handle exception
Log.d("sqt", "parse error" + e.getMessage());
}
return null;
}
}
五、应用
附加几个完整代码
本文转载于:
上一篇: PS简单制作漂亮的立体描边彩色绳子
下一篇: ai怎么设计豹纹花纹的手提包?
推荐阅读
-
Android学习--封装成json数据和解析json数据
-
Android JSON数据解析
-
Android - 手动解析Json数据(学习笔记一)
-
Android入门——数据解析之使用GSON解析JSON字符串(二)
-
Android 入门第六讲05-JSON解析第三方框架Gson(GSON框架使用方法,GSON解析Json数据(json对象,对象嵌套,数组,对象数组,json对象嵌套JSON对象数组))
-
Android随手笔记44之JSON数据解析
-
Android json数据解析详解及实例代码
-
Android之解析JSON数据示例(android原生态,FastJson,Gson)
-
Android编程实现根据经纬度查询地址并对获取的json数据进行解析的方法
-
Android随手笔记44之JSON数据解析