Android - 如何将JSON对象添加到sharedPreferences?

3
我想将数据追加到现有的JSON对象中,并将数据保存为字符串,其结构如下所示。
"results":[
          {
             "lat":"value",
             "lon":"value"
          }, 
          {
             "lat":"value",
             "lon":"value"

          }
        ]

如何做得正确?
我尝试过类似这样的方法,但没有成功。
// 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","{}");                  
}

谢谢任何建议。

你为什么要将完整的JSON对象保存在SharedPreferences中? - Mick
问题是关于创建JSON结构,而不是关于在共享首选项中保存JSON字符串的目的。我认为这是在Android中使用SQL的更简单的解决方案。 - redrom
创建JSON结构?你是什么意思? - kupsef
我想将新对象附加到旧对象上,以获得与我的问题中相似的JSON结构。 - redrom
这个答案将最好地解决你的问题。 - arslan haktic
显示剩余2条评论
2个回答

8

我认为更容易实现的方法是使用Gson

如果你正在使用gradle,可以将其添加到你的依赖项中。

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

要使用它,您需要为需要加载的对象定义类。在您的情况下,应该像这样:
// file MyObject.java
public class MyObject {
    List<Coord> results = new ArrayList<Coord>();    

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

然后,每当您需要时,只需使用它来进行Json的转换:

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);

3

SharedPreferences只能存储基本类型,例如String、integer、long等,因此不能用它来存储对象。但是,你可以使用sharedPreferences.putString()存储Json字符串。


是的,我在保存之前将创建的JSON转换为字符串,使用jsonData.toString()。问题是关于创建JSON结构,而不是关于在共享首选项中保存JSON字符串的目的。 - redrom
抱歉,我不太明白,您是想编辑您的 JSON 对象并在 sharedPreferences 中编辑该值吗? - Rogue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接