导包:
implementation 'com.google.code.gson:gson:2.8.1'
1.写一个json类
数据:
//数据
private String json="{\"page\":\"88\",\"address\":[{\"name\":\"第零个\"},{\"name\":\"第一个\"},{\"name\":\"第二个\"},{\"name\":\"第三个\"},{\"name\":\"第四个\"},{\"name\":\"第五个\"}]}";
alt+s
public class bbbb {
/**
* page : 88
* address : [{"name":"第零个"},{"name":"第一个"},{"name":"第二个"},{"name":"第第三个"},{"name":"第四个"},{"name":"第五个"}]
*/
private String page;
private List<AddressBean> address;
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public List<AddressBean> getAddress() {
return address;
}
public void setAddress(List<AddressBean> address) {
this.address = address;
}
public static class AddressBean {
/**
* name : 第零个
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
2.主函数
public class MainActivity extends AppCompatActivity {
private SharedPreferences user;
//数据
private String json="{\"page\":\"88\",\"address\":[{\"name\":\"第零个\"},{\"name\":\"第一个\"},{\"name\":\"第二个\"},{\"name\":\"第三个\"},{\"name\":\"第四个\"},{\"name\":\"第五个\"}]}";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//sp存储初始化
user = getSharedPreferences("User", Context.MODE_PRIVATE);
//存入数据
initvidio();
}
private void initvidio() {
List<com.example.administrator.myapplication.bbbb.AddressBean> list = new ArrayList<>();
Gson gson = new Gson();
//解析数据
bbbb bbbb = gson.fromJson(json, bbbb.class);
List<com.example.administrator.myapplication.bbbb.AddressBean> address = bbbb.getAddress();
//循环存入集合
for (int i = 0; i <address.size() ; i++) {
list.add(address.get(i));
}
//再将集合转为String字符串
String data = gson.toJson(list);
SharedPreferences.Editor edit = user.edit();
//存入sp
edit.putString("listStr", data);
edit.commit();
}
//获取集合
public void getsp(){
//获取对应listStr的数据
String data = user.getString("listStr", "");
Gson gson = new Gson();
Type listType = new TypeToken<List<com.example.administrator.myapplication.bbbb.AddressBean>>() {
}.getType();
//将得到的数据转成集合
List<com.example.administrator.myapplication.bbbb.AddressBean> list = gson.fromJson(data, listType);
for (int i = 0; i <list.size() ; i++) {
Log.d("aaaaaa", "getsp: "+list.get(i).getName());
}
}
//点击事件
public void cc(View view) {
getsp();
}
}
4.主布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/tbsView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:onClick="cc"
>
</RelativeLayout>
</LinearLayout>