Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gson.toJson: CharSequence passed to Appendable does not implement toString() #1702

Closed
Marcono1234 opened this issue May 21, 2020 · 1 comment · Fixed by #1703
Closed

Gson.toJson: CharSequence passed to Appendable does not implement toString() #1702

Marcono1234 opened this issue May 21, 2020 · 1 comment · Fixed by #1703
Labels

Comments

@Marcono1234
Copy link
Collaborator

Marcono1234 commented May 21, 2020

When calling Gson.toJson(..., Appendable) and Appendable is not an instance of Writer, then Gson creates a CharSequence which does not fulfill the toString() requirements:

Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.

Contrived example:

static class MyAppendable implements Appendable {
    private final StringBuilder stringBuilder = new StringBuilder();
    
    @Override
    public Appendable append(char c) throws IOException {
        stringBuilder.append(c);
        return this;
    }
    
    @Override
    public Appendable append(CharSequence csq) throws IOException {
        if (csq == null) {
            append("null");
        } else {
            append(csq, 0, csq.length());
        }
        return this;
    }
    
    public Appendable append(CharSequence csq, int start, int end) throws IOException {
        if (csq == null) {
            csq == "null";
        }
        
        // According to doc, toString() must return string representation
        String s = csq.toString();
        stringBuilder.append(s, start, end);
        return this;
    }
}

public static void main(String[] args) {
    MyAppendable myAppendable = new MyAppendable();
    new Gson().toJson("test", myAppendable);
    // Prints `com.` (first 4 chars of `com.google.gson.internal.Streams.AppendableWriter.CurrentWrite`)
    System.out.println(myAppendable.stringBuilder);
}
@Marcono1234
Copy link
Collaborator Author

Marcono1234 commented Jul 26, 2022

This is actually a duplicate of #527 (though maybe this issue here can be kept open because it includes a self-contained reproduction example)?

@Marcono1234 Marcono1234 added the bug label Aug 3, 2022
eamonnmcmanus pushed a commit that referenced this issue Aug 3, 2022
…toString (#1703)

* Gson.toJson creates CharSequence which does not implement toString

* Improve Streams.AppendableWriter.CurrentWrite test

* Make setChars package-private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant