JSON定义:(javascript object Notation的简称)一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性,可以在不同平台间进行数据交换。
1、JSON特点:
(1)json数据是一系列键值对的集合;
(2)json已经被大多数开发人员,在网络数据的传输当中应用非常广泛;
(3)json相对于xml来讲解析稍微方便一些。
2、JSON与XML比较
(1)json和xml的数据可读性基本相同;
(2)json和xml同样拥有丰富的解析手段;
(3)json相对于xml来讲,数据体积小;
(4)json与javascrpit的交互更加方便;
(5)json对数据的描述性相对较差;
(6)JSON的速度要远远快于XML。
一、设计界面
1、布局文件
打开activity_main.xml文件。
输入以下代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存JSON文件" />
<Button
android:id="@+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读取JSON文件" />
</LinearLayout>
二、程序文件
打开“src/com.genwoxue.filejson/MainActivity.java”文件。
然后输入以下代码:
package com.genwoxue.filejson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity {
private Button btnSave=null;
private Button btnRead=null;
private File file=null;
private static final String FILENAME="json.txt";
private StringBuffer info=null;
private String bookName[]=new String[]{"跟我学Android","从零开始学Android"};
private String author[]=new String[]{"蒋老夫子","蒋老夫子"};
private String publisher[]=new String[]{"人民邮电出版社","清华大学出版社"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSave=(Button)super.findViewById(R.id.save);
btnRead=(Button)super.findViewById(R.id.read);
btnSave.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
PrintStream ps=null;
JSONArray bookArray=new JSONArray();
for(int i=0;i<MainActivity.this.bookName.length;i++){
JSONObject object=new JSONObject();
try {
object.put("bookname", MainActivity.this.bookName[i]);
object.put("author",MainActivity.this.author[i]);
object.put("publisher",MainActivity.this.publisher[i]);
} catch (JSONException e) {
e.printStackTrace();
}
bookArray.put(object);
}
//判断外部存储卡是否存在
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();
return;
}
//初始化File
String path=Environment.getExternalStorageDirectory().toString()
+File.separator
+"genwoxue"
+File.separator
+FILENAME;
file=new File(path);
//如果当前文件的父文件夹不存在,则创建genwoxue文件夹
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
try {
ps=new PrintStream(new FileOutputStream(file));
ps.print(bookArray.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally{
if(ps!=null)
ps.close();
}
}
});
btnRead.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
info=new StringBuffer();
//判断外部存储卡是否存在
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();
return;
}
//判断文件是否存在
String path=Environment.getExternalStorageDirectory().toString()+File.separator+"genwoxue"+File.separator+FILENAME;
file=new File(path);
if(!file.exists()){
Toast.makeText(getApplicationContext(), "XML文件不存在!", Toast.LENGTH_LONG).show();
return;
}
//解析JSON文件
try {
InputStream input=new FileInputStream(file);
//InputStream转换为字符串
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
int n;
while ((n = input.read(b))!= -1){
buffer.append(new String(b,0,n));
}
//JSON解析
List<Map<String,Object>> books=MainActivity.this.parseJson(buffer.toString());
Iterator<Map<String,Object>> iter=books.iterator();
//遍历列表,获取书籍信息
while(iter.hasNext()){
Map<String,Object> map=iter.next();
info.append(map.get("bookname")).append("☆☆☆\n");
info.append(map.get("author")).append("☆☆☆\n");
info.append(map.get("publisher")).append("☆☆☆\n");
}
}catch(Exception e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), info.toString(), Toast.LENGTH_LONG).show();
}
});
}
/*
* 定义JSON解析方法parseJson()
*/
public List<Map<String,Object>> parseJson(String s) throws Exception{
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++){
Map<String,Object> map=new HashMap<String,Object>();
JSONObject object=array.getJSONObject(i);
map.put("bookname",object.getString("bookname"));
map.put("author", object.getString("author"));
map.put("publisher", object.getString("publisher"));
list.add(map);
}
return list;
}
}
三、配置文件
打开“AndroidManifest.xml”文件。
然后输入以下代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.genwoxue.filejson"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.genwoxue.filejson.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
注意:由于要进行读写外部存储卡操作,故而需要在AndroidManifest.xml文件中添加两项权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
四、运行结果