android中list数据与json互转

首先看主Activity:

package com.example.test;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView  test = (TextView) findViewById(R.id.jsons);
        Gson gson = new Gson();
        List list = new ArrayList();
        UserInfo user = new UserInfo(1001, "张三");
        list.add(user);
        list.add(user);
        list.add(user);
        String str = gson.toJson(list);
        test.setText(str);
        SavaData(str);
        System.out.println(str);

    }



    private void SavaData(String str) {
        // TODO Auto-generated method stub
        SharedPreferences  sharedPreferences = getSharedPreferences("test",0);
        SharedPreferences.Editor  editor = sharedPreferences.edit();
        editor.putString("list",str);
        editor.commit();
        System.out.println("保存数据成功!");
    }



    public void On_showData(View view){

        SharedPreferences  sharedPreferences = getSharedPreferences("test",Context.MODE_PRIVATE);
        String  jsondata = sharedPreferences.getString("list", "null");
        Gson gson = new Gson();
        if (!jsondata.equals("null")) {
            List list = gson.fromJson(jsondata, new TypeToken>() {}.getType());
            for(int i = 0; i < list.size() ; i++)
            {
                UserInfo p = list.get(i);
                 System.out.println(p.toString());
            }
            Toast.makeText(MainActivity.this, ""+list, 0).show();
        }

    }




}

实体类:

package com.example.test;

public class UserInfo {


    private Integer userId;


    private String userName;


    @Override
    public String toString() {
        return "UserInfo [userId=" + userId + ", userName=" + userName + "]";
    }


    public Integer getUserId() {
        return userId;
    }


    public void setUserId(Integer userId) {
        this.userId = userId;
    }


    public String getUserName() {
        return userName;
    }


    public void setUserName(String userName) {
        this.userName = userName;
    }


    public UserInfo(Integer userId, String userName) {
        super();
        this.userId = userId;
        this.userName = userName;
    }






}

需要的架包:
google官方json工具

效果图:
android中list数据与json互转_第1张图片

你可能感兴趣的