shaigan1782 / apex-library

Automatically exported from code.google.com/p/apex-library
0 stars 0 forks source link

valueToString returns invalid JSON ("}") if JSONObject is empty. #2

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

This should fail, but does not:

1. System.assertEquals('}', new JSONObject().ValueToString());

What is the expected output? What do you see instead?

new JSONObject().ValueToString() should return "{}", not "}"

Please provide any additional information below.

Because ValueToString appends trailing commas to all values, it removes the
last comma in its return statement:

ret.substring(0,ret.length()-1) + '}'

This, of course, is buggy if no values were appended.

Fixes are: 

a. add a trailing space to the "ret" initializer:

string ret = '{ '; // note trailing space

or

b. abandon the substring call (which is performant in java but not
necessarily other languages - unsure of how Apex handles it) and instead
append leading commas for all values except the first..

public String valueToString() {
  string ret = '{';
  for ( string key: this.keys() ) {
    if (ret.size() > 1) ret += ',';
    ret += '"' + key + '": ' + this.getvalue(key).valueToString();
  }
  return ret + '}';  
}

Original issue reported on code.google.com by finnh...@gmail.com on 24 May 2010 at 1:33

GoogleCodeExporter commented 9 years ago
Oops, that should be "ret.length()" instead of "ret.size()" in option (b).

Original comment by finnh...@gmail.com on 24 May 2010 at 1:35