【发布时间】:2021-02-19 06:22:42
【问题描述】:
我有一个接受字符串参数的类。然后我使用 sharedpreferences 来保留字符串。为此,我使用 gson.toJson 方法转换了输入字符串,然后将其作为 json 存储到 sharedpreferences 中。但是,我的 String 的 getter 方法需要将 String 的 json 对象转换回 gson。当初始输入字符串中没有空格时,转换有效。但是,当初始输入字符串中有空格时出现此错误
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $
这是类和参数:
public City(String name)
{
this.name=name;
Gson gson=new Gson();
sharedPreferences=context.getSharedPreferences("alternate_db",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(NAME_KEY,gson.toJson(this.name));
editor.apply();
}
这里是 String 的 getter 方法:
public String getName()
{
Gson gson=new Gson();
Type type=new TypeToken<String>(){}.getType();
return gson.fromJson(sharedPreferences.getString(NAME_KEY,null),type);
}
【问题讨论】:
-
我们需要查看您的 JSON,从源头修复您的 JSON 可能是这里最好的长期修复。