在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 类