Skip to content

Commit

Permalink
Fix an issue with generate_pretty and empty objects in the Ruby and J…
Browse files Browse the repository at this point in the history
…ava implementations
  • Loading branch information
chrisseaton committed Oct 7, 2020
1 parent 07c3404 commit b8c1c64
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
10 changes: 5 additions & 5 deletions java/src/json/ext/Generator.java
Expand Up @@ -334,13 +334,13 @@ void generate(final Session session, RubyHash object,

buffer.append((byte)'{');
buffer.append(objectNl);
object.visitAll(new RubyHash.Visitor() {
private boolean firstPair = true;

final boolean[] firstPair = new boolean[]{true};
object.visitAll(new RubyHash.Visitor() {
@Override
public void visit(IRubyObject key, IRubyObject value) {
if (firstPair) {
firstPair = false;
if (firstPair[0]) {
firstPair[0] = false;
} else {
buffer.append((byte)',');
buffer.append(objectNl);
Expand All @@ -360,7 +360,7 @@ public void visit(IRubyObject key, IRubyObject value) {
}
});
state.decreaseDepth();
if (objectNl.length() != 0) {
if (!firstPair[0] && objectNl.length() != 0) {
buffer.append(objectNl);
buffer.append(Utils.repeat(state.getIndent(), state.getDepth()));
}
Expand Down
6 changes: 4 additions & 2 deletions lib/json/pure/generator.rb
Expand Up @@ -332,8 +332,10 @@ def json_transform(state)
first = false
}
depth = state.depth -= 1
result << state.object_nl
result << state.indent * depth if indent
unless first
result << state.object_nl
result << state.indent * depth if indent
end
result << '}'
result
end
Expand Down
5 changes: 5 additions & 0 deletions tests/json_generator_test.rb
Expand Up @@ -92,6 +92,11 @@ def test_generate
end

def test_generate_pretty
json = pretty_generate({})
assert_equal(<<'EOT'.chomp, json)
{
}
EOT
json = pretty_generate(@hash)
# hashes aren't (insertion) ordered on every ruby implementation
# assert_equal(@json3, json)
Expand Down

0 comments on commit b8c1c64

Please sign in to comment.