Android开发之json解析案例详解
在Android开发中经常会访问网络,然后访问网络的时候,往往需要返回数据,但是在返回数据的过程中,往往返回的是Json数据或者xml数据,但本节讲述关于访问网络返回json格式的数据并进行解析,进行详细的讲解:
在代码中已经进行了详细的说明,下面主要粘贴代码:并进行简单的说明:
1.此主Activity包含了主要的代码,里面包含了解析json数据的方法,由于本例较小,所有没有分开,原则上应该是分类的。
[java]
package com.shine.yihutuandui;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
private Button back;
private ListView main_yihutuandui_lv;
private String display_info;
private List<HospitalTuanDuiBean> listarray;
private LVAdapter adapter;
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 301:
try {
listarray = getTopBeansJson(getServiceDataJson());
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new LVAdapter(MainActivity.this, listarray);
main_yihutuandui_lv.setAdapter(adapter);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
init();
}
private void init() {
main_yihutuandui_lv = (ListView) this
.findViewById(R.id.main_yihutuandui_lv);
back=(Button) this.findViewById(R.id.main_yihutuandui_back);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
new Thread(new Runnable() {
@Override
public void run() {
display_info = getHttpData();
System.out.println(display_info.toString()
+ "=======获取的信息json==============");
Message msg = new Message();
msg.what = 301;
handler.sendMessage(msg);
}
}).start();
}
//在assert文件夹下面获取图片
public Bitmap getAssertDrawable(String name) {
Bitmap bmp = null;
AssetManager am = MainActivity.this.getAssets();
try {
InputStream is = am.open(name);
bmp = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
/
补充:移动开发 , Android ,