'How to update element value in JsonObject?

I have a json file with parameters name and hit.

[{
    "name": "pavan",
    "hit": true   
}]

I would like to update name and hit to

[{
    "name": "sai",
    "hit": false
}]

I tried using put but it is not updating the values.

protected Void doInBackground(Void... voids) {

      /*  x = new ArrayList<Entry>();
        y = new ArrayList<String>();*/
        try {
            URL url=new URL("https://api.myjson.com/bins/1854yb");
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
            String line="";
            while (line!=null)
            {
                line=bufferedReader.readLine();
                data=data+line;
            }
            JSONArray JA=new JSONArray(data);
            for(int i=0;i<JA.length();i++)
            {
                JSONObject JO= (JSONObject) JA.get(i);
                singleparsed="Name:"+JO.get("name")+"\n"+
                        "Hit:"+JO.get("hit");

                JO.put("name","sai");
                JO.put("hit",false);

                dataparsed=dataparsed+singleparsed;
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

I want to update any element in that file, but it's not working.



Solution 1:[1]

You can override the value as you want putting the same key.

[ { "name": "pavan", "hit": true } ]

JsonObject jsonObj = new JsonObject();
jsonObj .put("name", "Sai");
jsonObj .put("hit", false); 

Solution 2:[2]

We can use JSON Object request instead of String request in Volley.

JSONObject obj = JSONObject()
obj.put("name", "xxx")
obj.put("hit", false)

Log.i("OutPut : ",obj.toString())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chandan Yadav
Solution 2