首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Android应用资源中使用JSON文件

在Android应用资源中使用JSON文件
EN

Stack Overflow用户
提问于 2011-06-15 04:33:30
回答 5查看 102.3K关注 0票数 94

假设我的应用程序的原始资源文件夹中有一个包含JSON内容的文件。我如何将其读入到应用程序中,以便解析JSON?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-06-15 04:46:31

参见openRawResource。像这样的东西应该是有效的:

代码语言:javascript
复制
InputStream is = getResources().openRawResource(R.raw.json_file);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
    Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    int n;
    while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
    }
} finally {
    is.close();
}

String jsonString = writer.toString();
票数 155
EN

Stack Overflow用户

发布于 2017-06-09 22:57:07

Kotlin现在是Android的官方语言,所以我认为这对某些人很有用

代码语言:javascript
复制
val text = resources.openRawResource(R.raw.your_text_file)
                                 .bufferedReader().use { it.readText() }
票数 128
EN

Stack Overflow用户

发布于 2014-06-04 04:00:23

我使用@kabuko的答案创建了一个对象,该对象使用Gson从参考资料中的JSON文件加载:

代码语言:javascript
复制
package com.jingit.mobile.testsupport;

import java.io.*;

import android.content.res.Resources;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


/**
 * An object for reading from a JSON resource file and constructing an object from that resource file using Gson.
 */
public class JSONResourceReader {

    // === [ Private Data Members ] ============================================

    // Our JSON, in string form.
    private String jsonString;
    private static final String LOGTAG = JSONResourceReader.class.getSimpleName();

    // === [ Public API ] ======================================================

    /**
     * Read from a resources file and create a {@link JSONResourceReader} object that will allow the creation of other
     * objects from this resource.
     *
     * @param resources An application {@link Resources} object.
     * @param id The id for the resource to load, typically held in the raw/ folder.
     */
    public JSONResourceReader(Resources resources, int id) {
        InputStream resourceReader = resources.openRawResource(id);
        Writer writer = new StringWriter();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(resourceReader, "UTF-8"));
            String line = reader.readLine();
            while (line != null) {
                writer.write(line);
                line = reader.readLine();
            }
        } catch (Exception e) {
            Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e);
        } finally {
            try {
                resourceReader.close();
            } catch (Exception e) {
                Log.e(LOGTAG, "Unhandled exception while using JSONResourceReader", e);
            }
        }

        jsonString = writer.toString();
    }

    /**
     * Build an object from the specified JSON resource using Gson.
     *
     * @param type The type of the object to build.
     *
     * @return An object of type T, with member fields populated using Gson.
     */
    public <T> T constructUsingGson(Class<T> type) {
        Gson gson = new GsonBuilder().create();
        return gson.fromJson(jsonString, type);
    }
}

要使用它,您需要执行类似于以下操作的操作(该示例在InstrumentationTestCase中):

代码语言:javascript
复制
   @Override
    public void setUp() {
        // Load our JSON file.
        JSONResourceReader reader = new JSONResourceReader(getInstrumentation().getContext().getResources(), R.raw.jsonfile);
        MyJsonObject jsonObj = reader.constructUsingGson(MyJsonObject.class);
   }
票数 26
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6349759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档