Luke Batley
Luke Batley

Reputation: 2402

change a value of a Name() within a JSON Object Android

Hi i have a JSONObject that i have turned into an Array looped through that array for a variable to see if it exists if not create one i need to then write this back to the array then back into the JSON Object heres hat i have got so far but can't quite figure out how to write values back to a JSON Object?

public static void updateLocalDataWithObject(Context activityContext, JSONObject fullNetworkDataFromFile) throws JSONException{

             JSONObject fullNetworkfile = fullNetworkDataFromFile.getJSONObject("data");
             JSONObject tempUserDict = fullNetworkfile.getJSONObject("user");
             String user_pref_club = tempUserDict.getString("primary_club_id");
             Log.v("globals", "3.)user_pref_club = " + user_pref_club);
             JSONObject userClubsDict = fullNetworkfile.getJSONObject("user_clubs");
             Log.v("globals", "userClubsDict = " + userClubsDict);

             if(userClubsDict.length()!= 0){

                 JSONArray userClubsDictKeys = new JSONArray();          
                 userClubsDictKeys=userClubsDict.names();

                 ArrayList<String> stringArray = new ArrayList<String>();
                 for(int i = 0, count = userClubsDictKeys.length(); i< count; i++)
                 {
                     try {
                         JSONObject jsonObject = userClubsDictKeys.getJSONObject(i);
                         stringArray.add(jsonObject.toString());
                     }
                     catch (JSONException e) {
                         e.printStackTrace();
                     }
                 }

                 for(String myString : stringArray){
                     Log.v("globals", "myString = " + myString);

                 }

                 Log.v("globals", "ARRAY userClubsDictKeys = " + userClubsDictKeys);
                 String clubID = userClubsDictKeys.getString(0);
                 Log.v("globals", "clubID = " + clubID);

                 if(user_pref_club =="" || (userClubsDictKeys.getString(0) == null)) user_pref_club = clubID; 

heres what gets logged out. i can't show the full data because its sensitive and have been instructed not to post it. but what im trying to do is write the vale of clubID to a new keyvalue pair in a JSONArray and then back to a JSONObject

03-01 12:00:51.269: V/globals(1085): ARRAY userClubsDictKeys = ["6496","16885"]
03-01 12:00:51.269: V/globals(1085): clubID = 6496


             } 

Upvotes: 0

Views: 3558

Answers (1)

Mokus
Mokus

Reputation: 3350

If I understand you correctly, you want to add values to a JSONArray/JSONObject.

To add a value to a JSONArray use

JSONArray json = new JSONArray();
json.put(<value>);

-OR-

json.put(<index>, <value>);

To add a value to a JSONObject use

JSONObject json = new JSONObject();
json.put("<key>", <value>);

Upvotes: 2

Related Questions