在没有了解Android之前,以为跟C++一样,解析json数据都是外部开源库来处理的,但是Android自带就有json解析器!言归正传,使用Android原生的Json解析器来解析json数据,这里只跟大家提及需要注意的一点:使用JSONObject时,需要加上try、catch处理异常。不加的话,Android Studio编译时会提示错误!json数据解析的示例代码如下:
package com.yzbt.gsontest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class MainActivity extends Activity {
private String szJson = "{ \"weatherinfo\":{\"city\":\"北京\", \"cityid\" : \"101010100\", " +
"\"temp\" : \"18\", \"WD\" : \"东南风\", \"WS\" : \"1级\", \"SD\" : \"17 % \", " +
"\"WSE\" : \"1\", \"time\" : \"17:05\", \"isRadar\" : \"1\", \"Radar\" : \"JC_RADAR_AZ9010_JB\"," +
" \"njd\" : \"暂无实况\", \"qy\" : \"1011\", \"rain\" : \"0\"} }";
private String szJsonAry = "{\n" +
"\"games\" :\n" +
" [\n" +
" {\"url\" :\"http:://www.qq.com\",\"name\" :\"jyjh\",\"server\" :\"S123\"},\n" +
" {\"url\" :\"http:://www.yy.com\",\"name\" :\"sjhz\",\"server\" :\"S456\"},\n" +
" {\"url\" :\"http:://www.sina.com\",\"name\" :\"ttxy\",\"server\" :\"S500\"}\n" +
" ]\n" +
"}";
private TextView mTextViewJson;
private TextView mTextViewJsonAry;
private TextView mTextViewWriteJson;
private TextView mTextViewReadJson;
private File mFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewJson = (TextView) findViewById(R.id.tv_json);
mTextViewJsonAry = (TextView) findViewById(R.id.tv_jsonary);
mTextViewWriteJson = (TextView)findViewById(R.id.tv_writejson);
mTextViewReadJson = (TextView)findViewById(R.id.tv_readjson);
mFile = new File(getFilesDir(),"games.json");//获取到应用在内部的私有文件夹下对应的games.json文件
((TextView)findViewById(R.id.tv_file)).setText("getFilesDir() : " + getFilesDir().toString());
try {
JSONObject root = new JSONObject(szJson);
JSONObject weatherinfo = root.getJSONObject("weatherinfo");
String city = weatherinfo.optString("city");
String cityid = weatherinfo.optString("cityid");
String WD = weatherinfo.optString("WD");
String WS = weatherinfo.optString("WS");
String SD = weatherinfo.optString("SD");
String WSE = weatherinfo.optString("WSE");
String time = weatherinfo.optString("time");
//执行效率:StringBuilder > StringBuffer > String
StringBuilder _builder = new StringBuilder()
.append("city:" + city)
.append("\ncityid:" + cityid)
.append("\nWD:" + WD)
.append("\nWS:" + WS)
.append("\nSD:" + SD)
.append("\nWSE:" + WSE)
.append("\ntime:" + time);
String strTemp = _builder.toString();
mTextViewJson.setText(strTemp);
Log.i("@@@ weatherinfo", strTemp);
System.out.printf("@@@ weatherinfo : %s", strTemp);
} catch (JSONException e) {
e.printStackTrace();
}
///
try {
JSONObject root2 = new JSONObject(szJsonAry);
JSONArray ary = root2.getJSONArray("games");
StringBuilder _builder2 = new StringBuilder();
Integer len = ary.length();//数组大小
for (Integer i=0; i<len; i++){
JSONObject _obj = ary.getJSONObject(i);
String url = _obj.optString("url");
String name = _obj.optString("name");
String server = _obj.optString("server");
_builder2.append("\nurl : " + url)
.append("\nname : " + name)
.append("\nserver : " + server);
}
String strTemp2 = _builder2.toString();
mTextViewJsonAry.setText(strTemp2);
Log.i("@@@ games", strTemp2);
System.out.printf("@@@ games : %s", strTemp2);
} catch (JSONException e) {
e.printStackTrace();
}
///
try{
JSONObject root3 = new JSONObject();//实例一个JSONObject对象
root3.put("updatetime","20180325");//对其添加一个数据
JSONArray games = new JSONArray();//实例一个JSON数组
JSONObject game1 = new JSONObject();//实例一个game1的JSON对象
game1.put("url","https://www.baidu.com");//对game1对象添加数据
game1.put("name","csgogogo");
game1.put("server","s100");
JSONObject game2 = new JSONObject();//实例一个game2的JSON对象
game2.put("url","https://www.aliyun.com");//对game2对象添加数据
game2.put("name","thisiskandy");
game2.put("server","s200");
games.put(0, game1);//将game1对象添加到JSON数组中去,角标为0
games.put(1, game2);//将game2对象添加到JSON数组中去,角标为1
root3.put("games", games);//然后将JSON数组添加到名为root的JSON对象中去
mTextViewWriteJson.setText(root3.toString());
FileOutputStream fos = new FileOutputStream(mFile);//创建一个文件输出流
fos.write(root3.toString().getBytes());//写入JSON数据
fos.close();//关闭输出流
}catch (JSONException e) {
e.printStackTrace();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
///
try {
FileInputStream fis = new FileInputStream(mFile);//获取一个文件输入流
InputStreamReader isr = new InputStreamReader(fis);//读取文件内容
BufferedReader bf = new BufferedReader(isr);//将字符流放入缓存中
String line;//定义一个用来临时保存数据的变量
StringBuilder sb = new StringBuilder();//实例化一个字符串序列化
while((line = bf.readLine()) != null){
sb.append(line);//将数据添加到字符串序列化中
}
//关闭流
fis.close();
isr.close();
bf.close();
JSONObject root = new JSONObject(sb.toString());//用JSONObject进行解析
String updatetime = root.getString("updatetime");//获取字符串类型的键值对
JSONArray array = root.getJSONArray("games");//获取JSON数据中的数组数据
StringBuilder _builder = new StringBuilder().append("updatetime : " + updatetime);
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);//遍历得到数组中的各个对象
String url = object.getString("url");//获取第一个值
String name = object.getString("name");//获取第二个值
String server = object.getString("server");//获取第三个值
_builder.append("\nurl : " + url)
.append("\nname : " + name)
.append("\nserver : " + server);
}
mTextViewReadJson.setText(_builder.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
运行结果如下: