基本使用:

1
2
3
4
5
6
7
8
9
10
11
public static void public static void main(String\[\] args) {
Project project;
Gson gson = new Gson();
String jsonString = gson.toJson(project); //将对象转换成Json字符串

//使用jsonString
Type type new TypeToken<Project>(){}.getType; //保存对象类型
project projectFromJson = gson.fromJson(jsonString, type)

//使用projectFromJson
}

在android中使用Json转换的封装类(将数据放在SharedPreferences中):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class ModelUtils {

private static Gson gsonForSerialization = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriSerializer())
.create();

private static Gson gsonForDeserialization = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriDeserializer())
.create();

private static String PREF_NAME = "models";

public static void save(Context context, String key, Object object) {
SharedPreferences sp = context.getApplicationContext().getSharedPreferences(
PREF\_NAME, Context.MODE\_PRIVATE);

String jsonString = gsonForSerialization.toJson(object);
sp.edit().putString(key, jsonString).apply();
}

public static <T> T read(Context context, String key, TypeToken<T> typeToken) {
SharedPreferences sp = context.getApplicationContext().getSharedPreferences(
PREF\_NAME, Context.MODE\_PRIVATE);
try {
return gsonForDeserialization.fromJson(sp.getString(key, ""), typeToken.getType());
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}

private static class UriSerializer implements JsonSerializer<Uri> {
@Override
public JsonElement serialize(Uri src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}

private static class UriDeserializer implements JsonDeserializer<Uri> {
@Override
public Uri deserialize(JsonElement src, Type srcType, JsonDeserializationContext context) throws JsonParseException {
return Uri.parse(src.getAsString());
}
}

}

SharedPreferences基本:

1
2
3
4
5
6
7
8
9
10
11
What’s Shared Preferences? - It’s basically a key-value storage 写:

// How to write to Shared Preferences
// How to write to Shared Preferences
SharedPreferences sp = context.getSharedPreferences(PREF\_NAME, Context.MODE\_PRIVATE);
// We need an Editor object to make preference changes.
SharedPreferences.Editor editor = sp.edit();
editor.putString("key", "value");
editor.putInt("int", 10);
// Save the edits!
editor.apply();

读:

1
2
3
4
5
// How to read from Shared Preferences
SharedPreferences sp = context.getSharedPreferences(PREF\_NAME, Context.MODE\_PRIVATE);
// It’s like a hash map! Easy!
String value = sp.getString("key", "");
int intValue = sp.getInt("int", 0);