Java 如何将json文件添加到android项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40565078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add json file to android project
提问by Jeff Louzada
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
我只是想将 .json 文件添加到我的 android studio 项目中。我遇到的大部分内容都是您创建一个文件夹并将其添加到那里,但我想简单地将它移到应用程序下。这是我的项目图片
采纳答案by CommonsWare
I want to simply move it over under app
我想简单地将它移到应用程序下
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.
如果您的字面意思是想要拥有app/something.json
,欢迎您将文件放在那里,但它不会与您的应用程序打包在一起,并且在运行时您将无法使用它。
If you want to ship the JSON with your app, you have four major options:
如果您想将 JSON 与您的应用程序一起发送,您有四个主要选项:
Put it in
assets/
and read it in usingAssetManager
and itsopen()
method to get anInputStream
Put it in
res/raw/
and read it in usingResources
and itsopenRawResource()
methodHardcode it as a string in Java code
Write yourself a code generator that converts JSON into a Java class that you would access like you do the code-generated
R
andBuildConfig
classes
把它放进
assets/
去读它在使用AssetManager
和它的open()
方法得到一个InputStream
把它放进
res/raw/
去读它在使用Resources
和它的openRawResource()
方法将其硬编码为 Java 代码中的字符串
自己写一个代码生成器,转换成JSON Java类,你会获得像你这样的代码生成
R
和BuildConfig
类
It is possible that such a code generator already exists. I have a rudimentary Gradle pluginthat does this, as an example that I'll be including in the next update of my book.
可能已经存在这样的代码生成器。我有一个基本的 Gradle 插件可以做到这一点,作为一个例子,我将包含在我的书的下一次更新中。
回答by Morozov
Put it androidTest/assets/
Just create file
, like a SomeFile.json
把它 androidTest/assets/ 就创建file
,就像一个SomeFile.json