Files
JSON-java/src/test/java/org/json/junit/data/FromJsonKeyBindingExample.java
T
Lyin-OTTF 88b6be9f84 Clarify fromJson(Class) Javadoc: type registry does not exist
The fromJson(Class) Javadoc claimed that only classes "explicitly supported
and registered within the JSONObject context" can be deserialized, and
declared an IllegalArgumentException for classes outside that set. No such
registry exists: fromJson instantiates any class with a no-arg constructor and
writes every non-static declared field whose name matches a JSON key, widening
access with setAccessible(true). Private and transient fields are populated,
and JSONPropertyIgnore does not apply because it only suppresses the bean to
JSONObject direction.

The binding rules are already released, so changing them here would break
existing users. Instead document what actually happens, point out that binding
is driven by whatever keys the JSON contains, and replace the non-existent
IllegalArgumentException with the JSONException the method really throws.

Adds JSONObjectTest#jsonObjectParseFromJson_10 to pin the current binding
behavior so the documentation cannot drift from the implementation again. The
test bean is named FromJsonKeyBindingExample and its fields spell out how they
are declared (privateString, privateBoolean, transientString,
ignoredGetterBoolean), so the test reads as a binding example rather than as a
scenario.

Fixes #1076
2026-10-26 08:38:38 +08:00

40 lines
1.0 KiB
Java

package org.json.junit.data;
import org.json.JSONPropertyIgnore;
/**
* Bean used to pin down how {@code JSONObject#fromJson(Class)} binds JSON keys
* to fields: {@code privateString} and {@code privateBoolean} are private,
* {@code transientString} is transient, and {@code ignoredGetterBoolean} is
* hidden behind a getter annotated with {@code @JSONPropertyIgnore} (which only
* suppresses the bean to JSONObject direction).
*/
public class FromJsonKeyBindingExample {
public String displayName;
private boolean privateBoolean;
private String privateString;
private transient String transientString;
private boolean ignoredGetterBoolean;
public FromJsonKeyBindingExample() {
// Required for JSONObject#fromJson(Class<T>) tests.
}
public boolean isPrivateBoolean() {
return privateBoolean;
}
public String getPrivateString() {
return privateString;
}
public String getTransientString() {
return transientString;
}
@JSONPropertyIgnore
public boolean isIgnoredGetterBoolean() {
return ignoredGetterBoolean;
}
}