0

Hey Guys I am learning JSON right now. So at first I want to learn how to create one. So I wrote this code ...

public void writeJsonFile() {
    username = usernameField.getText().toString();
    password = passwordField.getText().toString();
    JSONObject jsonObject = new JSONObject();
    try{
        jsonObject.put("username", username);
        jsonObject.put("password", password);
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
}

But I have a Problem...How I can save the jSON file into the internal memory in the appfolder? And what is the code to call and read that file again?

Al Lelopath
  • 6,448
  • 13
  • 82
  • 139
mc.b
  • 93
  • 1
  • 4
  • 14

2 Answers2

0

You can call jsonObject.toString and then save and read like in the answer to this question. After reading a string from disk you would need to call

JSONObject jsonObject = new JSONObject(yourString);

to parse it back into a JsonObject.

There are also tools like Gson that help you do object to json serialization that can help avoid some of this work.

Community
  • 1
  • 1
Carl Poole
  • 1,970
  • 2
  • 23
  • 28
0

Saving the JSON per se is not really a good option. What you could do is:

  1. Transform the JSON file into a String and save the String using SharedPrefferences and when you get it from the SharedPrefferences transform it back into a JSON.
  2. Use a database (Realm), map your JSON to a model and save that model in the database.
  3. I wouldn't do either of those for Username/Password cases. But I would use SharedPrefferences and store both valued independently with different keys.

Don't forget to encrypt sensitive data in the SharedPrefferences.

If you really really want to save the info in a file, check this answer.

Community
  • 1
  • 1
Adrian Coman
  • 1,536
  • 17
  • 30
  • Okay, is it a bad way to save username and password in a txt. in the memory? – mc.b Mar 24 '17 at 19:04
  • 1
    Well, it's not saved in the memory. It's saved on the internal storage. And no, it's not a good idea to save it as plain text. You should encrypt the information. Edited main answer with link. – Adrian Coman Mar 24 '17 at 19:06