0

I have a class that takes in a String parameter. I then use sharedpreferences to preserve the String. To do this, I converted the input String using the gson.toJson method and then stored it into the sharedpreferences as a json. However, my getter method for the String requires the conversion of the json object of the String back to gson. The conversion works when there are no spaces in the initial input String. However, I get this error when there is a space within the initial input String

     com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 6 path $

Here is the class and parameter:

    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();
}

Here is the getter method for the String:

    public String getName()
{
    Gson gson=new Gson();
    Type type=new TypeToken<String>(){}.getType();
    return gson.fromJson(sharedPreferences.getString(NAME_KEY,null),type);
}
1
  • 1
    We need to see your JSON, and fixing your JSON at the source is probably the best long term fix here. Commented Feb 19, 2021 at 6:25

1 Answer 1

2

On the AS, the object class is first converted into a row and then converted into a character string. In this case, when a space is parsed, the end is parsed by default. As a result, an error is reported. Therefore, you need to convert the file to the JSON format in one step to avoid errors.

gson.fromJson(gson.toJson(sharedPreferences.getString(NAME_KEY,null),type));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.