繁体   English   中英

我如何将 android 游戏中的数据保存到本地 json 文件

[英]How i save data from android game to a local json file

我想将用户的数据保存在 json 文件中的内部 memory 但它不起作用有什么问题???? 这是代码.................................................. ..................................................... .....................

public JSONObject addToJson(Context context, String email,String password)throws Exception{
    String id_P = UUID.randomUUID().toString();
    JSONObject jsonObject = new JSONObject();

    jsonObject.put("id_P",id_P);
    jsonObject.put("Email",email);
    jsonObject.put("password",password);

    
    String j = jsonObject.toString();
    System.out.println(j);
    File file = new File(context.getFilesDir(),"dbApp.json");
    FileWriter fileWriter = new FileWriter(file);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(j);
    bufferedWriter.close();

    return jsonObject;
}

您可以使用不同的本地数据库,如 Room、Realm 等。但是对于

Writing:  you need to convert your JSON into String or Model class and then you can store into Database. 
Reading  : convert string into JSON or Model Class and use the same.

多看看https://realm.io/docs/java/latest/

Android 中的 Realm 数据库示例 您可以选择以下选项:

写作

User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();

阅读

RealmQuery<User> query = realm.where(User.class);

// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");

// Execute the query:
RealmResults<User> result1 = query.findAll();

// Or alternatively do the same all at once (the "Fluent interface"):
RealmResults<User> result2 = realm.where(User.class)
                              .equalTo("name", "John")
                              .or()
                              .equalTo("name", "Peter")
                              .findAll();

好吧,我不是这方面的专家,但我认为您应该这样做:

首先将此 JSON 转换器库添加到您的 build.gradle:

implementation 'com.google.code.gson:gson:2.8.6'

之后,您需要创建一个 model class ,您应该在其中对不同地图中的数据进行分类,注意:始终使用地图数组列表将无法正常工作:

Class Model{
Map<String ,String> userData;

 public Model(Map<String, String> setUserdata) {
    this.setUserdata = setUserdata;
}


         public void setSetUserdata(Map<String, String> setUserdata) {
          this.setUserdata = setUserdata;
          }


}  

好的,然后要设置数据,您应该创建一个 Map ,然后初始化 class 并将其传递给 Map ,类似于:

Map<String ,String> userData=new HashMap<>();
        setUserdata.put("username","something");
        setUserdata.put("password","something");
Model model=new Model(userData);

现在您可以轻松地将其转换为 JSON: Gson gson = new Gson(); 字符串 json = gson.toJson(model);

您可以轻松地将其保存在文本格式的文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM