ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JSON 使用实例_2_Android 读取json文件

2021-02-24 17:02:12  阅读:177  来源: 互联网

标签:JsonObject JSON public json new Android id Resources


在Android 项目中,可以把预先 JSON 数据保存在  res/raw 的目录下, 然后再通过Resources.openRawResource 读取。

Resources 对象可以通过Context 对象去获取。

public class Resources {
    public InputStream openRawResource(@RawRes int id) throws NotFoundException {
public abstract class Context {
    public abstract Resources getResources();

1. 保存json数据 (res/raw/ 目录下)

例如把 contents.json 保存在 res/raw 目录下

其中contents.json 的内容:


{
   "pageInfo": {
         "pageName": "abc",
         "pagePic": "http://example.com/content.jpg"
    },
    "posts": [
         {
              "post_id": "123456789012_123456789012",
              "actor_id": "1234567890",
              "picOfPersonWhoPosted": "http://example.com/photo.jpg",
              "nameOfPersonWhoPosted": "Jane Doe",
              "message": "Sounds cool. Can't wait to see it!",
              "likesCount": "2",
              "comments": [],
              "timeOfPost": "1234567890"
         }
    ]
}

2.  导入Gson 依赖

3. 读取json 文件,得到 JsonObject 对象

    private JsonObject load(int id){
        String json = "";

        try {
            InputStream inputStream = mContext.getResources().openRawResource(id);
            Writer writer = new StringWriter();
            char[] buffer = new char[inputStream.available()];
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            int n;
            while((n = reader.read(buffer)) != -1){
                log.info("load n="+n);
                writer.write(buffer, 0, n);
            }

            json = writer.toString();
        } catch (Exception e){
            log.error("load json error: "+e.getMessage());
        }

        return new Gson().fromJson(json, JsonObject.class);
    }
}

主要是得到InputStream后,通过BufferReader 读取, 最后写入到StringWriter 对象中。

4. 调用

JsonObject jsonObject = load(R.raw.contents);

其中, JsonObject 是Gson 依赖库的类, 也有JsonArray 表示数组, 注意区分org.json 库中的JSONObject 和JSONArray 类

标签:JsonObject,JSON,public,json,new,Android,id,Resources
来源: https://blog.csdn.net/whjk20/article/details/114027497

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有