Android - how to add JSON object to sharedPreferences?

android, json

Solution

I think the easier way to achieve that would be using Gson.

If you are using gradle you can add it to your dependencies

compile 'com.google.code.gson:gson:2.2.4'

To use it you need to define classes to the objects you need to load. In your case it would be something like this:

// file MyObject.java
public class MyObject {
    List<Coord> results = new ArrayList<Coord>();    

    public static class Coord {
        public double lat;
        public double lon;
}

Then just use it to go to/from Json whenever you need:

String jsonDataString = this.getSharedPreferencesStringValue(ctx, "positions", "last_positions");
Gson gson = new Gson();
MyObject obj = gson.fromJson(jsonDataString, MyObject.class);
// Noew obj contains your JSON data, so you can manipulate it at your will.
Coord newCoord = new Coord();
newCoord.lat = 34.66;
newCoord.lon = -4.567;
obj.results.add(newCoord);
String newJsonString = gson.toJson(obj);

Problem

I would like to append data into existing JSON object and save data as string into shared preferences with following structure. ``` "results":[ { "lat":"value", "lon":"value" }, { "lat":"value", "lon":"value" } ] ``` How can i do it right? I tried something like this, but without luck. ``` // get stored JSON object with saved positions String jsonDataString = this.getSharedPreferencesStringValue(ctx, "positions", "last_positions"); if (jsonDataString != null) { Log.i(AppHelper.APP_LOG_NAMESPACE, "JSON DATA " + jsonDataString); JSONObject jsonData = new JSONObject(jsonDataString); jsonData.put("lat", lat.toString()); jsonData.put("lon", lon.toString()); jsonData.put("city", city); jsonData.put("street", street); jsonData.put("date", appHelper.getActualDateTime()); jsonData.put("time", appHelper.getActualDateTime()); this.setSharedPreferencesStringValue(ctx, "positions", "last_positions", jsonData.toString()); } else { this.setSharedPreferencesStringValue(ctx, "positions", "last_positions","{}"); } ``` Thanks for any advice.

Original source

Related problems