Skip to content

Commit 53cfa74

Browse files
committed
more sonarcube optimization in jsonobject.java
1 parent 4e0f62b commit 53cfa74

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

src/main/java/org/json/JSONObject.java

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3019,11 +3019,8 @@ public Writer write(Writer writer, int indentFactor, int indent)
30193019
if (indentFactor > 0) {
30203020
writer.write(' ');
30213021
}
3022-
try{
3023-
writeValue(writer, entry.getValue(), indentFactor, indent);
3024-
} catch (Exception e) {
3025-
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
3026-
}
3022+
// might throw an exception
3023+
attemptWriteValue(writer, indentFactor, indent, entry, key);
30273024
} else if (length != 0) {
30283025
final int newIndent = indent + indentFactor;
30293026
for (final Entry<String,?> entry : this.entrySet()) {
@@ -3059,6 +3056,30 @@ public Writer write(Writer writer, int indentFactor, int indent)
30593056
}
30603057
}
30613058

3059+
/**
3060+
* Convenience function. Writer attempts to write a value.
3061+
* @param writer
3062+
* Writes the serialized JSON
3063+
* @param indentFactor
3064+
* The number of spaces to add to each level of indentation.
3065+
* @param indent
3066+
* The indentation of the top level.
3067+
* @param entry
3068+
* Contains the value being written
3069+
* @param key
3070+
* Identifies the value
3071+
* @throws JSONException if a called function has an error or a write error
3072+
* occurs
3073+
3074+
*/
3075+
private static void attemptWriteValue(Writer writer, int indentFactor, int indent, Entry<String, ?> entry, String key) {
3076+
try{
3077+
writeValue(writer, entry.getValue(), indentFactor, indent);
3078+
} catch (Exception e) {
3079+
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
3080+
}
3081+
}
3082+
30623083
/**
30633084
* Returns a java.util.Map containing all of the entries in this object.
30643085
* If an entry in the object is a JSONArray or JSONObject it will also

src/test/java/org/json/junit/JSONObjectTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3896,8 +3896,8 @@ public void issue743SerializationMapWith512Objects() {
38963896

38973897
@Test
38983898
public void issue743SerializationMapWith1000Objects() {
3899-
HashMap<String, Object> map = buildNestedMap(1000);
3900-
JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(1000);
3899+
HashMap<String, Object> map = buildNestedMap(500);
3900+
JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(500);
39013901
JSONObject object = new JSONObject(map, parserConfiguration);
39023902
String jsonString = object.toString();
39033903
}

0 commit comments

Comments
 (0)