我有latlng地理位置列表
ArrayList<Route> arrayList
我正在通过
保存 SharedPreferences prefeMain = MainActivitybatchGrp1.this.getSharedPreferences("APPLICATION", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefeMain.edit();
try {
Log.e("TASK","Success");
editor.putString("GROUPA", ObjectSerializer.serialize(arrayListLatLong));
} catch (IOException e) {
Log.e("TASK","Fail:: "+e);
e.printStackTrace();
}
editor.commit();
但是它给出了IOException
java.io.NotSerializableException: com.directions.route.Route
答案 0 :(得分:1)
如果某个类没有实现java.io.Serializable(就像你的情况那样),你可以将它转换为JSON并将JSON存储在SharedPreferences
上。
当然,您还需要从SharedPreferences
反序列化JSON字符串。
以下是使用流行的GSON库进行序列化/反序列化的示例:
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class GsonTest {
private static class Test1213 {
public Test1213(String name) {
this.name = name;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Test
void testConversion() throws IOException {
Gson gson = new Gson();
Test1213 john_doe1 = new Test1213("John Doe");
String john_doe = gson.toJson(john_doe1);
System.out.println(john_doe);
Test1213 test1213 = gson.fromJson(john_doe, Test1213.class);
assertThat(john_doe1.getName(), is(test1213.getName()));
}
}
此测试序列化为JSON并返回。
这是序列化的JSON:
{"name":"John Doe"}