本篇文章全部以示例为主,方便大家简单易懂!
{
"condition": "ooppp",
"data": [
{
"date": "2013-08-29 12:32:31",
"message": "xxxxxxxxxx",
"utime": "2013-08-29 12:32:31"
},
{
"date": "2013-08-29 12:32:31",
"message": "xxxxxxxxxx",
"utime": "2013-08-29 12:32:31"
},
{
"date": "2013-08-29 12:32:31",
"message": "xxxxxxxxxx",
"utime": "2013-08-29 12:32:31"
},
{
"date": "2013-08-29 12:32:31",
"message": "xxxxxxxxxx",
"utime": "2013-08-29 12:32:31"
}
],
"ischeck": "1",
"state": "0",
"status": "200",
"xxu": "61995"
}
把上面的解析出来:
str表示服务器返回来的字符串(上)
try {
JSONObject jo = new JSONObject(str);
System.out.println(jo.toString());
JSONArray ja = new JSONArray(jo.getString("data"));
System.out.println(ja.toString());
for (int i = 0; i < 4; i++) {
JSONObject temp = (JSONObject) ja.get(i);
System.out.println(temp.getString("date")+" "+temp.getString("message")+" "+temp.getString("utime"));
}
} catch (JSONException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
代码构建json字符串:一般以字符串的形式传给服务器
package sn.len.json;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class JSONActivity extends Activity {
private String jsondata;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
//调用构建JSON字符串方法
buildJson();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
//构建JSON字符串
public void buildJson() throws JSONException
{
JSONArray json=new JSONArray();
JSONObject jsonObj=new JSONObject();
for(int i=0;i<2;i++)
{
jsonObj.put("id", "001");
jsonObj.put("age", "20");
jsonObj.put("name", "snoanw");
//把每个数据当作一对象添加到数组里
json.put(jsonObj);
}
jsondata=json.toString();
Log.i("JSON", jsondata);
//调用解析JSON方法
parserJson(jsondata);
}
// 解析JSON字符串
public void parserJson(String jsondata) throws JSONException
{
//构建JSON数组对象
JSONArray json1=new JSONArray(jsondata);
for(int i=0;i<json1.length();i++)
{
JSONObject jsonObj2=json1.optJSONObject(i);
String id=jsonObj2.getString("id");
String age=jsonObj2.getString("age");
String name=jsonObj2.getString("name");
Log.i("JSONDATA", id+age+name);
}
}
}
构建成的样子:
[{"id":"001","name":"snonaw","age":"20"},{"id":"002","name":"chace","age":"23"}]
服务器返回的字符串:
{
"userbean": {
"Showname": "u75afu72c2u7684u7334u5b50",
"State": 1,
"Uid": "100196"
}
}
代码解析:builder.toString()代表请求服务器时,服务器返回的字符串
JSONObject jsonObject = new JSONObject(builder.toString()).getJSONObject("userbean");
String Uid;
String Showname;
String Avtar;
String State;
Uid = jsonObject.getString("Uid");
Showname = jsonObject.getString("Showname");
Avtar = jsonObject.getString("Avtar");
State = jsonObject.getString("State");
服务器返回的字符串:
{
"calendar": {
"calendarlist": [
{
"allDay": false,
"calendar_id": "1705",
"category_name": "u9ed8u8ba4u5206u7c7b",
"endshowtime": "1288931400",
"showtime": "1288927800",
"title": "(u4eb2u5b50)ddssd"
},
{
"allDay": false,
"calendar_id": "1706",
"category_name": "u9ed8u8ba4u5206u7c7b",
"endshowtime": "1288936800",
"showtime": "1288933200",
"title": "(u65c5u884c)"
}
]
}
}
代码解析服务器返回的字符串:builder.toString()同样代表服务器返回的字符串
SONObject jsonObject = new JSONObject(builder.toString()) .getJSONObject("calendar");
JSONArray jsonArray = jsonObject.getJSONArray("calendarlist");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject2 = (JSONObject)jsonArray.opt(i);
CalendarInfo calendarInfo = new CalendarInfo();
calendarInfo.setCalendar_id(jsonObject2.getString("calendar_id"));
calendarInfo.setTitle(jsonObject2.getString("title"));
calendarInfo.setCategory_name(jsonObject2.getString("category_name"));
calendarInfo.setShowtime(jsonObject2.getString("showtime"));
calendarInfo.setEndtime(jsonObject2.getString("endshowtime"));
calendarInfo.setAllDay(jsonObject2.getBoolean("allDay"));
calendarInfos.add(calendarInfo);
}
单数据 {'singer':{'id':1,'name':'tom','gender':'男'}}
多个数据 {'singers':[{'id':'2','name':'tom','gender':'男'},{'id':'3','name':'jerry','gender':'男'},{'id':'4','name':'jim','gender':'男'},{'id':'5','name':'lily','gender':'女'}]}
{
"singer": {
"gender": "男",
"id": 1,
"name": "tom"
}
}
{
"singers": [
{
"gender": "男",
"id": "2",
"name": "tom"
},
{
"gender": "男",
"id": "3",
"name": "jerry"
},
{
"gender": "男",
"id": "4",
"name": "jim"
},
{
"gender": "女",
"id": "5",
"name": "lily"
}
]
}
public class JsonActivity extends Activity {
/** Called when the activity is first created. */
private TextView tvJson;
private Button btnJson;
private Button btnJsonMulti;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvJson = (TextView) this.findViewById(R.id.tvJson);
btnJson = (Button) this.findViewById(R.id.btnJson);
btnJsonMulti = (Button) this.findViewById(R.id.btnJsonMulti);
btnJson.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// url
// String strUrl = "http://10.158.166.110:8080/AndroidServer/JsonServlet";
String strUrl = ServerPageUtil.getStrUrl(UrlsOfServer.JSON_SINGER);
//获得返回的Json字符串
String strResult = connServerForResult(strUrl);
//解析Json字符串
parseJson(strResult);
}
});
btnJsonMulti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String strUrl = ServerPageUtil.getStrUrl(UrlsOfServer.JSON_SINGERS);
String strResult = connServerForResult(strUrl);
//获得多个Singer
parseJsonMulti(strResult);
}
});
}
private String connServerForResult(String strUrl) {
// HttpGet对象
HttpGet httpRequest = new HttpGet(strUrl);
String strResult = "";
try {
// HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
// 获得HttpResponse对象
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 取得返回的数据
strResult = EntityUtils.toString(httpResponse.getEntity());
}
} catch (ClientProtocolException e) {
tvJson.setText("protocol error");
e.printStackTrace();
} catch (IOException e) {
tvJson.setText("IO error");
e.printStackTrace();
}
return strResult;
}
// 普通Json数据解析
private void parseJson(String strResult) {
try {
JSONObject jsonObj = new JSONObject(strResult).getJSONObject("singer");
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String gender = jsonObj.getString("gender");
tvJson.setText("ID号"+id + ", 姓名:" + name + ",性别:" + gender);
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
}
//解析多个数据的Json
private void parseJsonMulti(String strResult) {
try {
JSONArray jsonObjs = new JSONObject(strResult).getJSONArray("singers");
String s = "";
for(int i = 0; i < jsonObjs.length() ; i++){
JSONObject jsonObj = (JSONObject)jsonObjs.get(i);
int id = jsonObj.getInt("id");
String name = jsonObj.getString("name");
String gender = jsonObj.getString("gender");
s += "ID号"+id + ", 姓名:" + name + ",性别:" + gender+ "\n" ;
}
tvJson.setText(s);
} catch (JSONException e) {
System.out.println("Jsons parse error !");
e.printStackTrace();
}
}
}
共同学习,写下你的评论
评论加载中...
作者其他优质文章