json文件同XML文件一样,都是重要的编程语言格式,由于XML语言规范性较高,所以在数据传输方面大放异彩。但是由于JavaScript的大范围使用,json语言也变得越来越重要了。所以谷歌的Android Studio提供给我们方法让用户自定义解析json格式的文件。
json中{ }大括号是一个包含多种属性的文件;
json中[ ]中括号里有多个相同属性的文件;
具体步骤是通过使用JSONObject类里面的方法返回json语言的{}数据;
getJSONArray 方法是是返回json文件的[]里面的数据;
通过循环遍历可以得到返回的中括号里的数据。
<span style="font-size:18px;">import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class PaserJsonActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paser_json);
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
InputStream is = null;
try {
is = getResources().getAssets().open("jsonNews.txt");
br = new BufferedReader(new InputStreamReader(is));
String flag = "";
while ((flag = br.readLine()) != null) {
sb.append(flag);
}
//Json对象对应 json数据中{}大括号
JSONObject obj = new JSONObject(sb.toString());
//获得json数据大括号里的大括号
JSONObject obj1 = obj.getJSONObject("showapi_res_body");
JSONObject obj2 = obj1.getJSONObject("pagebean");
//json数组对应 json数据中[]
JSONArray ja = obj2.getJSONArray("contentlist");
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
if (jo.has("content")) { //有此属性则取之
String name = jo.getString("content");
Log.v("--------",name);
}
}
} catch (IOException e) {
Toast.makeText(this, "未找到该文件", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
</span>