Android-如何将JSON对象添加到sharedPreferences? [英] Android - how to add JSON object to sharedPreferences?

查看:334
本文介绍了Android-如何将JSON对象添加到sharedPreferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据追加到现有的JSON对象中,并将数据作为字符串保存到具有以下结构的共享首选项中.

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"

          }
        ]

我该怎么办?

我尝试过类似的方法,但是没有运气.

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","{}");                  
}

谢谢您的任何建议.

推荐答案

我认为更简单的方法是使用 Gson .

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

如果您正在使用gradle,则可以将其添加到依赖项中

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

然后只要需要,就可以使用它来进入/离开Json:

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

这篇关于Android-如何将JSON对象添加到sharedPreferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆