more sonarcube optimization in jsonobject.java

This commit is contained in:
marilynel 2025-09-07 12:41:37 -08:00
parent 4e0f62b1a6
commit 53cfa742a7
2 changed files with 28 additions and 7 deletions

View File

@ -3019,11 +3019,8 @@ public class JSONObject {
if (indentFactor > 0) { if (indentFactor > 0) {
writer.write(' '); writer.write(' ');
} }
try{ // might throw an exception
writeValue(writer, entry.getValue(), indentFactor, indent); attemptWriteValue(writer, indentFactor, indent, entry, key);
} catch (Exception e) {
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
}
} else if (length != 0) { } else if (length != 0) {
final int newIndent = indent + indentFactor; final int newIndent = indent + indentFactor;
for (final Entry<String,?> entry : this.entrySet()) { for (final Entry<String,?> entry : this.entrySet()) {
@ -3059,6 +3056,30 @@ public class JSONObject {
} }
} }
/**
* Convenience function. Writer attempts to write a value.
* @param writer
* Writes the serialized JSON
* @param indentFactor
* The number of spaces to add to each level of indentation.
* @param indent
* The indentation of the top level.
* @param entry
* Contains the value being written
* @param key
* Identifies the value
* @throws JSONException if a called function has an error or a write error
* occurs
*/
private static void attemptWriteValue(Writer writer, int indentFactor, int indent, Entry<String, ?> entry, String key) {
try{
writeValue(writer, entry.getValue(), indentFactor, indent);
} catch (Exception e) {
throw new JSONException("Unable to write JSONObject value for key: " + key, e);
}
}
/** /**
* Returns a java.util.Map containing all of the entries in this object. * Returns a java.util.Map containing all of the entries in this object.
* If an entry in the object is a JSONArray or JSONObject it will also * If an entry in the object is a JSONArray or JSONObject it will also

View File

@ -3896,8 +3896,8 @@ public class JSONObjectTest {
@Test @Test
public void issue743SerializationMapWith1000Objects() { public void issue743SerializationMapWith1000Objects() {
HashMap<String, Object> map = buildNestedMap(1000); HashMap<String, Object> map = buildNestedMap(500);
JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(1000); JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(500);
JSONObject object = new JSONObject(map, parserConfiguration); JSONObject object = new JSONObject(map, parserConfiguration);
String jsonString = object.toString(); String jsonString = object.toString();
} }