如何将json文件添加到android项目 [英] how to add json file to android project
问题描述
我只是想将.json文件添加到我的android studio项目中.我遇到的大多数问题都在您创建一个文件夹并将其添加到此处,但是我想简单地将其移至应用程序下. 这是我的项目图片
I am simply trying to add a .json file into my android studio project. Most of what I have run into has you create a folder and add it there but I want to simply move it over under app. Here Is my project image
推荐答案
我想简单地将其移至应用程序下
I want to simply move it over under app
如果从字面上讲您想拥有app/something.json
,欢迎将文件放在此处,但该文件不会与您的应用打包在一起,并且在运行时将不可用.
If you literally mean that you want to have app/something.json
, you are welcome to put the file there, but it will not be packaged with your app, and it will not be available to you at runtime.
如果您希望将JSON与您的应用一起发布,则有四个主要选择:
If you want to ship the JSON with your app, you have four major options:
-
将其放入
assets/
中,并使用AssetManager
及其open()
方法读取以获取InputStream
Put it in
assets/
and read it in usingAssetManager
and itsopen()
method to get anInputStream
将其放入res/raw/
中,并使用Resources
及其openRawResource()
方法读取它
Put it in res/raw/
and read it in using Resources
and its openRawResource()
method
使用Java代码将其硬编码为字符串
Hardcode it as a string in Java code
为自己编写一个代码生成器,该代码生成器将JSON转换为您可以访问的Java类,就像执行代码生成的R
和BuildConfig
类
Write yourself a code generator that converts JSON into a Java class that you would access like you do the code-generated R
and BuildConfig
classes
这样的代码生成器可能已经存在.我有一个基本的Gradle插件,例如我将包含在我的书的下一次更新中.
It is possible that such a code generator already exists. I have a rudimentary Gradle plugin that does this, as an example that I'll be including in the next update of my book.
这篇关于如何将json文件添加到android项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!