Skip to content

Doubt about parsing the string of "null" #54

Open
@Alanscut

Description

@Alanscut

Hi Andres @aalmiray, in the latest verion 3.0.0, in function JSONObject.element(key, value), if the input value is a valid JSON formatted string, it will still output a string instead of converting it to JSONObject/JSONArray. But if the string is "null", it will be transformed to a JSONNull, which I think it maybe unreasonable, so I fix it to output the string "null".

public void test_object_element_null_string() {
    JSONObject object = new JSONObject();
    object.element("key1", "{}");
    object.element("key2", "[]");
    object.element("key3", "null");
    Assertions.assertTrue(object.get("key1") instanceof String);
    Assertions.assertTrue(object.get("key2") instanceof String);
    Assertions.assertTrue(object.get("key3") instanceof JSONNull);
    System.out.println(object);

    // {"key1":"{}","key2":"[]","key":null}
    "{}" JSONObject format --> string
    "[]" JSONArray format --> string
    "null" JSONNull formt --> JSONNull
}

However, in function JSONArray.element(), if the string is a valid JSON formatted string, it will be transformed to a JSONArray/JSONObject/JSONNull.

/**
 * Append a String value. This increases the array's length by one.<br>
 * The string may be a valid JSON formatted string, in tha case, it will be
 * transformed to a JSONArray, JSONObject or JSONNull.
 *
 * @param value A String value.
 *
 * @return this.
 */
public JSONArray element(String value) {
    return element(value, new JsonConfig());
}

It is because of this way of handling the input string in JSONArray that we can never get an JSONArray like this: ["null", "string"]...

public void test_array_element_null_string() {
    JSONArray array = new JSONArray();
    array.element("\"null\"");
    array.element("null");
    System.out.println(array);

    // ["\"null\"",null]
}

I wonder why the function of element() in JSONArray and JSONObject handle the input value in diffrent way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions