[英]Create, Write, Edit JSON file in Android Studio
I would like to create a JSON file in the internal storage of the phone, to store data.我想在手机的内部存储器中创建一个 JSON 文件,用于存储数据。 I want to be able to add objects ("configX") to the file and then read the data.
我希望能够将对象(“configX”)添加到文件中,然后读取数据。
It should look something like this:它应该看起来像这样:
{
"config1": {
"component1": "url",
"component2": "url",
"component3": "url"
},
"config2": {
"component1": "url",
"component2": "url",
"component3": "url"
}
}
I can create a JSON file like this:我可以像这样创建一个 JSON 文件:
public void saveToJson(){
JSONObject json = new JSONObject();
try {
json.put("component1", "url");
json.put("component2", "url");
String jsonString = json.toString();
FileOutputStream fos = this.openFileOutput("jsonfile", Context.MODE_PRIVATE);
fos.write(jsonString.getBytes());
fos.close();
Log.d("JSON" , json.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
But how to put the components in the config object?但是如何将组件放入配置 object 中? And how to retrieve the data?
以及如何检索数据?
EDIT 1:编辑1:
https://stackoverflow.com/a/62474912/11652860 https://stackoverflow.com/a/62474912/11652860
Thanks for the very detailed answer, I'm doing something wrong.感谢您提供非常详细的答案,我做错了。 I have an Activity where I put and save data to the json file:
我有一个活动,我将数据放入并保存到 json 文件中:
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
Map<String, String> config1 = new HashMap<>();
config1.put("component1", "url1");
config1.put("component2", "url1");
config1.put("component3", "url1");
Map<String, Map<String, String>> map = new HashMap<>();
map.put("config1", config1);
Data data = new Data(map);
Gson gson = new Gson();
String json = gson.toJson(data);
FileOutputStream fos = null;
try {
fos = webViewActivity.this.openFileOutput("jsonfile", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(json.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And a fragment where I load the data:还有一个我加载数据的片段:
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
public void load(){
FileInputStream fis = null;
try {
fis = getContext().openFileInput("jsonfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null){
sb.append(text).append("\n");
Gson gson = new Gson();
String json = gson.toJson(text);
Data data = gson.fromJson(json, Data.class);
String url = data.getMap().get("config1").get("component1");
frameTV.setText(url);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The saving and loading parts must be wrong, but they worked for getting text out a text file保存和加载部分一定是错误的,但它们可以从文本文件中获取文本
EDIT 2:编辑2:
I found the problem, I wasn't loading and saving properly:我发现了问题,我没有正确加载和保存:
SAVING:保存:
String filename = "jsonfile.txt";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(json.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
LOADING:加载:
FileInputStream fis = getContext().openFileInput("jsonfile.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class);
String priceURL = data.getMap().get("config1").get("url1");
EDIT 3:编辑 3:
My problem now is that I need to create the file once and then check if the file exists, if it does I need to check if config1 exists if it doesn't I need to put config in the file.我现在的问题是我需要创建一次文件,然后检查文件是否存在,如果存在,我需要检查 config1 是否存在,如果不存在,我需要将 config 放入文件中。
But I can't check if config1 exists because I get: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Map com.a.app.ui.app.appFragment$Data.getMap()
But I can't check if config1 exists because I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Map com.a.app.ui.app.appFragment$Data.getMap()
I check if it exists by doing:我通过以下方式检查它是否存在:
Boolean configTest = data.getMap().containsKey("config1");
if(!configTest){}
How can I create the file and check the data without getting a NullPointerException?如何在不出现 NullPointerException 的情况下创建文件并检查数据?
Thank you for helping me !感谢你们对我的帮助 !
Google's Gson library will be helpful in this case. Google 的 Gson 库在这种情况下会有所帮助。
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
public class Data {
private Map<String, Map<String, String>> map;
public Data() {
}
public Data(Map<String, Map<String, String>> map) {
this.map = map;
}
public Map<String, Map<String, String>> getMap() {
return map;
}
public void setMap(Map<String, Map<String, String>> map) {
this.map = map;
}
}
Map<String, String> config1 = new HashMap<>();
config1.put("component1", "url1");
config1.put("component2", "url1");
config1.put("component3", "url1");
Map<String, String> config2 = new HashMap<>();
config2.put("component1", "url1");
config2.put("component2", "url1");
config2.put("component3", "url1");
Map<String, Map<String, String>> map = new HashMap<>();
map.put("config1", config1);
map.put("config2", config2);
Data data = new Data(map);
Gson gson = new Gson();
String json = gson.toJson(data);
You can now save this json in a file in a text format.您现在可以将此 json 保存在文本格式的文件中。
Now when reading, load the content of the text file in a String say 'jsonString'.现在在阅读时,将文本文件的内容加载到一个字符串中,比如“jsonString”。
Deserialize the jsonString to Java Object将jsonString反序列化为Java Object
Data data = gson.fromJson(json, Data.class);
String url = data.getMap().get("config1").get("component1");
Map<String, String> config3 = new HashMap<>();
config3.put("component1", "url1");
config3.put("component2", "url1");
config3.put("component3", "url1");
data.getMap().put("config3", config3);
Follow again these steps to save configs再次按照这些步骤保存配置
Or You can manually edit the text file to add configs according to the predefined format.或者您可以手动编辑文本文件以根据预定义的格式添加配置。
{
"maps":{
"config2":{
"component1":"url1",
"component2":"url1",
"component3":"url1"
},
"config1":{
"component1":"url1",
"component2":"url1",
"component3":"url1"
}
}
}
Please consider using https://github.com/google/gson .请考虑使用https://github.com/google/gson 。 You will be working with class instance rather than with JSONObject.
您将使用 class 实例而不是 JSONObject。 Much more convenient.
方便很多。
Just to give you the idea of what you can do:只是为了让您了解您可以做什么:
public class TestClass {
private final Map<String, String> config1;
private final Map<String, String> config2;
public TestClass(Map<String, String> config1, Map<String, String> config2) {
this.config1 = config1;
this.config2 = config2;
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, String> config1 = new HashMap<String, String>();
config1.put("hello1.1", "world1.1");
config1.put("hello1.2", "world1.2");
Map<String, String> config2 = new HashMap<String, String>();
config2.put("hello2.1", "world2.1");
config2.put("hello2.2", "world2.2");
TestClass testClass = new TestClass(config1, config2);
Log.d("zzz", gson.toJson(testClass));
The above prints:以上打印:
{
"config1": {
"hello1.1": "world1.1",
"hello1.2": "world1.2"
},
"config2": {
"hello2.1": "world2.1",
"hello2.2": "world2.2"
}
}
You can go back and force between json string and the entity itself.您可以返回 go 并在 json 字符串和实体本身之间强制。 To edit, you only need to work with object - natural and convenient way.
要进行编辑,您只需要使用 object - 自然便捷的方式。
This is how you create multiple Objects in a single JSON object:这是在单个 JSON object 中创建多个对象的方式:
//Creating first Object
JSONObject config1 = new JSONObject();
try {
json.put("component1", "url");
json.put("component2", "url");
json.put("component2", "url");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Creating second object
JSONObject config2 = new JSONObject();
try {
json.put("component1", "url");
json.put("component2", "url");
json.put("component2", "url");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject finalJSON = new JSONObject();
try {
//Adding both objects in one single object
json.put("config1", config1);
json.put("config2", config2);
String jsonString = finalJSON.toString();
FileOutputStream fos = this.openFileOutput("jsonfile", Context.MODE_PRIVATE);
fos.write(jsonString.getBytes());
fos.close();
Log.d("JSON" , json.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
This will give you the desired output.这将为您提供所需的 output。 Also, if in case you want to make any object an array, you can use
JSONArray
for that.此外,如果您想将任何 object 设为数组,则可以使用
JSONArray
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.