0

Here is code in Android Studio in that I am creating a json object with username and password of one user and storing it to json array (just to have more users). In fact a am converting it to String before storing. So How can I read and store it back to json array that contains my json object?

Here is code

public void storeJson() {

            jobj = new JSONObject();

            try {
                jobj.put("username",usern);
                jobj.put("password",passwd);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            jarray = new JSONArray();
            jarray.put(jobj);
            String str = jarray.toString();

            try {
                fileOutputStream =  openFileOutput(passwordFile, 0);
                fileWriter = new OutputStreamWriter(fileOutputStream);

                try {
                    fileWriter.write(str);
                    fileWriter.flush();
                    fileWriter.close();
                    Toast.makeText(getApplicationContext(), "File Written", Toast.LENGTH_LONG).show();
                    username.setText("");
                    password.setText("");

                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "Write Error", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

}

kyriakosSt
  • 1,754
  • 2
  • 15
  • 33
Bati_IUT
  • 11
  • 1
  • try this `new Gson().fromJson(response, new TypeToken() { }.getType())` with this code you can convert string json to your object – ali zarei Dec 12 '17 at 18:10
  • I am a beginner in this sphere and don't get it clearly. But there is no Gson library builtin. and I have String variable read from file. And I need to convert it back to json as it was initially. – Bati_IUT Dec 12 '17 at 18:53
  • 1
    I guess i managed this. All I needed was to write::: jarray = new JSONArray(temp_pwd); int len = jarray.length(); jobj = new JSONObject(); jobj = jarray.getJSONObject(0); String strr = jobj.getString("username"); String sstr = jobj.getString("password"); – Bati_IUT Dec 12 '17 at 19:49

0 Answers0