我这个项目是一个自己写的Json文件,然后读取文件内容的天气显示App
- 数据准备,在main目录下新建一个文件夹assets,再在此目录下新建一个json文件,名字自己随意,只要后面对应就行,我这里是weather.json
具体代码和项目文件组织结构图如下:
weather.json:
[
{"city": "北京", "weather": "晴", "temp": "20℃/30℃ ", "pm": "3", "wind": "2级"},
{"city": "上海", "weather": "多云", "temp": "22℃/30℃ ", "pm": "2.6", "wind": "3级"},
{"city": "广州", "weather": "有雨", "temp": "20℃/27℃ ", "pm": "2", "wind": "5级"},
{"city": "哈尔滨", "weather": "小雪", "temp": "-8℃/-1℃ ", "pm": "2.1", "wind": "1级"}
]
图中的天气icon图片可以去http://www.icosky.com/iconset/weather-2-icons/下载,背景图自己去选择。
2.导入Gson.jar包,步骤如下:
选中项目,点击鼠标右键,选择Open Module Setting,进入Project Structure界面,选择Dependencies,选择app,然后点击右侧的方框中的+,Library Dependency,进入Add Library Dependency界面,输入com.google.code.gson:gson,点击Search,选择你需要的版本即可。
3.准备读取本本地的 json 数据文件并解析 json 数据的工具类JsonUtils.java
public class JsonUtils {
private static JsonUtils instance; // 单例模式
private JsonUtils(){
}
public static JsonUtils getInstance(){
if(instance==null){
instance = new JsonUtils();
}
return instance;
}
/**
* 读取输入文件内容
* @param is 输入流
* @return json 字符串
*/
private String read(InputStream is){
BufferedReader reader = null; // 带缓存的读取器
StringBuilder sb = null; // 字符串构造器
String line = null; // 过程变量
try{
sb = new StringBuilder();
// 从 is 中读取内容
reader = new BufferedReader(new InputStreamReader(is));
while((line = reader.readLine()) != null){
sb.append(line);
sb.append("\n");
}
}catch(Exception ex){
ex.printStackTrace();
}finally {
try{
if(reader!=null) reader.close();
if(is!=null) is.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
return sb.toString();
}
/**
* 从数据文件中读取json数据
* @param context 上下文信息
* @return List<Weather> 城市天气数据集合
*/
public List<Weather> getWeatherListFromFile(Context context){
List<Weather> list = new ArrayList<>();
InputStream is = null;
try{
is = context.getResources().getAssets().open("weather.json");
String json = read(is); // 调用自定义的方法 读取 json 字符串
Gson gson = new Gson();
// 通过反射机制,定义一类型解析器
Type listType = new TypeToken<List<Weather>>(){
}.getType();
// 使用 gson 库实例,解析json 字符串,交将结果存入 list 中去
list = gson.fromJson(json, listType);
}catch(Exception ex){
ex.printStackTrace();
}finally {
try{
if(is!=null) is.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
return list;
}
}
- 准备实体类Weather.java
public class Weather