什么是jason
一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据交换。JSON采用兼容性很高的文本格式,同时也具备类似于C语言体系的行为。
jason格式规范
JSON数据在名称/值对中;数据由逗号分隔;花括号保存对象;方括号保存数组;
Json数据的书写格式:名称/值对 比如: "person":"coder-pig" 。
Array里面可以包含对象(object):
[ {"id":"1","name":"基神","age":"18"}, //一个无序的名称/值对集合即为一个对象
{"id":"2","name":"B神","age":"18"},
{"id":"3","name":"曹神","age":"18"} ]
//这是一个对象数组
对象(object)中可以包含Array
{"root":[ {"id":"001","name":"小猪"},{"id":"002","name":"小猫"},
{"id":"003","name":"小狗"} ],
"total":3,
"success":true
}
可以对象嵌套子对象,子对象再嵌套数组
{"calendar":
{"calendarlist": [ {"id":"001","name":"小猪"}, {"id":"002","name":"小猫"} ] }
}
利用jason存储音乐列表信息
新建一个音乐项类
public class MusicItem {
//jason数据的名称
public static final String JSON_NAME = "name";
public static final String JSON_PATH = "path";
public static final String SINGER = "singer";
public static final String LENGTH = "length";
private String name, singer, path;
private int mLength;
public MusicItem (String name, String singer, String path, int length) {
this.name = name;
this.path = path;
this.singer = singer;
mLength = length;
}
public MusicItem (JSONObject json) throws JSONException {
name = json.getString(JSON_NAME);
path = json.getString(JSON_PATH);
singer = json.getString(SINGER);
mLength = json.getInt(LENGTH);
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSinger() { return singer; }
public void setSinger(String singer) { this.singer = singer; }
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
public JSONObject toJSON() throws JSONException {
//转换成jason数据
JSONObject json = new JSONObject();
json.put(JSON_NAME, name);
json.put(JSON_PATH, path);
json.put(SINGER, singer);
json.put(LENGTH, mLength);
return json;
}
}
JSONObject是系统中有关JSON定义的基本单元,其包含一个键值对值。利用JSONObject的put方法可以添加键值对到一个jason对象。
新建一个音乐列表jason序列化类
public class MusicJSONSerializer {
public static final String MUSIC_JSON_SERIALIZER = "musicJSONSerializer";
private Context mContext;
private String mFileName;
public MusicJSONSerializer(String mFileName, Context mContext) {
this.mFileName = mFileName;
this.mContext = mContext;
}
public void saveMusic(ArrayList<MusicItem> musics) throws JSONException,IOException {
JSONArray array = new JSONArray();
//获取一个JSONArray对象
for (MusicItem music : musics) {
array.put(music.toJSON());
//将musicItem数据转换成Jason数据然后添加到JSONArray中
}
Writer writer = null;
try {
//保存Jason数据到文件中
OutputStream out = mContext.openFileOutput(mFileName,Context.MODE_PRIVATE);
//Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist.
writer = new OutputStreamWriter(out);
writer.write(array.toString());
}finally {
if (writer != null) {
writer.close();
}
}
}
public ArrayList<MusicItem> loadMusic() throws IOException,JSONException {
ArrayList<MusicItem> musics = new ArrayList<MusicItem>();
BufferedReader reader = null;
try {
//读取文件中的jason数据
InputStream in = mContext.openFileInput(mFileName);
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder jsonString = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
jsonString.append(line);
}
//通过JSONTokener的nextValue()来获得JSONObject对象,
//然后再通过JSONObject对象来做进一步的解析。
JSONArray array = (JSONArray)new JSONTokener(jsonString.toString()).nextValue();
for (int i = 0; i < array.length(); i++) {
musics.add(new MusicItem(array.getJSONObject(i)));
}
}catch (FileNotFoundException e) {
Log.i(MUSIC_JSON_SERIALIZER,"未找到相关的Jason文件");
}finally {
if (reader != null) {
reader.close();
}
}
return musics;
}
}
SONTokener是系统为JSONObject和JSONArray构造器解析JSON source string的类,它可以从source string中提取数值信息。
JSONStringer这个类可以帮助快速和便捷的创建JSONtext。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntaxrules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。
String myString = new JSONStringer().object().key("name")
.value("小猪").endObject().toString();
使用GSON解析JSON数据
Gson是一个Java库,它不仅可以把Java对象转化为Json格式,它也能将一段Json格式的字符串转化为相对于的Java对象。Gson适用于所有Java对象,即使是那些你不知道源代码的对象。
一. 添加gson库
1.首先,在自己的android studio的项目中把gson库添加进来,右键 app 选择open module settings
2.选择app,然后点击 Dependencies,在点击3步中的Library dependency(依赖的库)
3.在1所指的弹出的收索框中收索gson,然后点击2 所指的收索,然后下面就会出现最新的gson库,点击OK
4.点击上图OK后,gson库就出现在了dependency中了,这个时候还得点击 2所指的OK(确认)按钮。
二. 添加GsonFormat插件
三. 将一段Json格式的字符串转化为相对于的Java对象
生成的Weather类
public class Weather {
/**
* type : forecast1d
* weatherinfo : [{"city":"北京","cityid":"1","temp1":"22℃","temp2":"10℃","weather":"晴","ptime":"11:00"},
* {"city":"上海","cityid":"2","temp1":"24℃","temp2":"12℃","weather":"晴","ptime":"11:00"}]
*/
private String type;
/**
* city : 北京
* cityid : 1
* temp1 : 22℃
* temp2 : 10℃
* weather : 晴
* ptime : 11:00
*/
private List<WeatherinfoBean> weatherinfo;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<WeatherinfoBean> getWeatherinfo() {
return weatherinfo;
}
public void setWeatherinfo(List<WeatherinfoBean> weatherinfo) {
this.weatherinfo = weatherinfo;
}
public static class WeatherinfoBean {
private String city;
private String cityid;
private String temp1;
private String temp2;
private String weather;
private String ptime;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
public String getTemp1() {
return temp1;
}
public void setTemp1(String temp1) {
this.temp1 = temp1;
}
public String getTemp2() {
return temp2;
}
public void setTemp2(String temp2) {
this.temp2 = temp2;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getPtime() {
return ptime;
}
public void setPtime(String ptime) {
this.ptime = ptime;
}
}
}
然后利用fromJason( )方法将jasonString转换成Weather对象
AssetManager am = getResources().getAssets();
InputStream is = am.open(testjason.txt);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(is));
StringBuilder strBuilder = new StringBuilder();
String line = "";
while ( (line = bufReader.readline()) != null ) {
strBuilder.append(line);
}
String jasonString = strBuilder.toString();
Gson gson = new Gson();
Weather weather = gson.fromJson(jasonString, Weather.class);
利用Gson的toJason方法可以将某个Weather对象装换成jason string。