【问题标题】:java error when trying to parse json object with a space using gson尝试使用 gson 解析带有空格的 json 对象时出现 java 错误
【发布时间】: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 可能是这里最好的长期修复。

标签: java android


【解决方案1】:

在AS上,对象类先转换成一行,再转换成字符串。在这种情况下,解析空格时,默认解析结尾。结果,报错。因此,您需要将文件一步转换为 JSON 格式以避免错误。 gson.fromJson(gson.toJson(sharedPreferences.getString(NAME_KEY,null),type));

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 2023-02-25
    • 2021-05-01
    • 1970-01-01
    • 2012-11-07
    • 2017-08-17
    • 1970-01-01
    • 2014-10-19
    • 2014-07-29
    相关资源
    最近更新 更多