mirror of
https://github.com/fankes/JSON-java-compat.git
synced 2025-09-08 11:34:43 +08:00
Add a config flag to disable whitespace trimming
This commit is contained in:
@@ -431,6 +431,9 @@ public class XML {
|
||||
&& jsonObject.opt(config.getcDataTagName()) != null) {
|
||||
context.accumulate(tagName, jsonObject.opt(config.getcDataTagName()));
|
||||
} else {
|
||||
if (!config.shouldTrimWhiteSpace()) {
|
||||
removeEmpty(jsonObject, config);
|
||||
}
|
||||
context.accumulate(tagName, jsonObject);
|
||||
}
|
||||
}
|
||||
@@ -445,6 +448,48 @@ public class XML {
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* This method removes any JSON entry which has the key set by XMLParserConfiguration.cDataTagName
|
||||
* and contains whitespace as this is caused by whitespace between tags. See test XMLTest.testNestedWithWhitespaceTrimmingDisabled.
|
||||
* @param jsonObject JSONObject which may require deletion
|
||||
* @param config The XMLParserConfiguration which includes the cDataTagName
|
||||
*/
|
||||
private static void removeEmpty(final JSONObject jsonObject, final XMLParserConfiguration config) {
|
||||
if (jsonObject.has(config.getcDataTagName())) {
|
||||
final Object s = jsonObject.get(config.getcDataTagName());
|
||||
if (s instanceof String) {
|
||||
if (isStringAllWhiteSpace(s.toString())) {
|
||||
jsonObject.remove(config.getcDataTagName());
|
||||
}
|
||||
}
|
||||
else if (s instanceof JSONArray) {
|
||||
final JSONArray sArray = (JSONArray) s;
|
||||
for (int k = sArray.length()-1; k >= 0; k--){
|
||||
final Object eachString = sArray.get(k);
|
||||
if (eachString instanceof String) {
|
||||
String s1 = (String) eachString;
|
||||
if (isStringAllWhiteSpace(s1)) {
|
||||
sArray.remove(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sArray.isEmpty()) {
|
||||
jsonObject.remove(config.getcDataTagName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isStringAllWhiteSpace(final String s) {
|
||||
for (int k = 0; k<s.length(); k++){
|
||||
final char eachChar = s.charAt(k);
|
||||
if (!Character.isWhitespace(eachChar)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method tries to convert the given string value to the target object
|
||||
@@ -594,7 +639,7 @@ public class XML {
|
||||
*/
|
||||
public static JSONObject toJSONObject(Reader reader, XMLParserConfiguration config) throws JSONException {
|
||||
JSONObject jo = new JSONObject();
|
||||
XMLTokener x = new XMLTokener(reader);
|
||||
XMLTokener x = new XMLTokener(reader, config);
|
||||
while (x.more()) {
|
||||
x.skipPast("<");
|
||||
if(x.more()) {
|
||||
|
Reference in New Issue
Block a user