sessionStorage不存储原始对象

时间:2016-11-07 09:40:59

标签: javascript javascript-objects session-storage

我有一个通过执行SDK功能获得的对象。当我尝试将对象存储在会话存储中并检索对象时,检索到的对象看起来与原始对象相同,但是当我对新对象执行操作时,我收到错误。

var xyzObject = some_function();

sessionStorage.setItem("xyzObject",xyzObject);

var obj = JSON.parse(sessionStorage.getItem("xyzObject"));

obj.some_other_function();

由于 obj.some_other_function 不是函数,因此显示错误。而 xyzObject.some_other_function 的效果非常好。

2 个答案:

答案 0 :(得分:1)

尝试

public class LazyAdapterHelpCentersAlava extends BaseAdapter {

    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    HashMap<String, String> song;
    Typeface tf; 

    Context context;

    public LazyAdapterHelpCentersAlava(Context ctx, ArrayList<HashMap<String, String>> d, String font) {
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        tf = Typeface.createFromAsset(activity.getAssets(), font);
        context = ctx;   // Initialize the context here. 
    }

    // .. Here are the other functions ... Omitted for clarity

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
        vi = inflater.inflate(R.layout.list_row_help_centers, null);

        // Here are the other lines in getView function. Omitted for clarity

        web = (TextView)vi.findViewById(R.id.web);
        web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Need to start an Activity here   
                Intent newActivity = new Intent(context, NewActivity.class);
                context.startActivity(newActivity); 
            }
        });

        return vi;
    }
}

使用以下方式检索:

sessionStorage.setItem('xyzObject', JSON.stringify(xyzObject);

答案 1 :(得分:1)

您无法在sessionStorage或localStorage中存储对象。唯一可能的方法是对对象进行字符串化并将其保存在sessionStorage中,并在从sessionStorage接收对象时将对象解析为JSON。

var xyzObject = some_function();

sessionStorage.setItem("xyzObject",JSON.stringify(xyzObject));

var stringData = sessionStorage.getItem("xyzObject");

var obj = JSON.parse(stringData);

obj.some_other_function();