Class JSONUtils
- java.lang.Object
-
- io.microsphere.json.JSONUtils
-
- All Implemented Interfaces:
Utils
public abstract class JSONUtils extends java.lang.Object implements Utils
Utility class for generating and manipulating JSON strings.This abstract class provides a set of static methods to append different types of data into a JSON-formatted string using a
StringBuilder
. It supports primitive types, their wrapper classes, arrays (both primitive and object), collections likeMap
,Iterable
, and custom objects through recursive value appending.Example Usage
StringBuilder builder = new StringBuilder(); // Appending simple key-value pairs: JSONUtils.append(builder, "name", "John Doe"); // Result: {"name":"John Doe"} // Appending nested objects: JSONUtils.append(builder, "user", Map.of("id", 1, "active", true)); // Result: {"user":{"id":1,"active":true}} // Appending arrays: JSONUtils.append(builder, "numbers", new int[]{1, 2, 3}); // Result: {"numbers":[1,2,3]} // Appending collections: JSONUtils.append(builder, "tags", List.of("java", "json", "utils")); // Result: {"tags":["java","json","utils"]}
- Since:
- 1.0.0
- Author:
- Mercy
- See Also:
StringBuilder
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, boolean value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, boolean[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, byte value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, byte[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, char value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, char[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, double value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, double[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, float value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, float[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, int value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, int[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, long value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, long[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, short value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, short[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Boolean value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Boolean[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Byte value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Byte[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Character value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Character[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Double value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Double[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Float value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Float[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Integer value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Integer[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Long value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Long[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Object value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.reflect.Type value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Short value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Short[] values)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.String value)
static void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.String[] values)
static <T> void
append(java.lang.StringBuilder jsonBuilder, java.lang.String name, T[] values)
static java.lang.StringBuilder
appendName(java.lang.StringBuilder jsonBuilder, java.lang.String name)
static void
appendValue(java.lang.StringBuilder jsonBuilder, java.lang.Object value)
static java.lang.Class<?>
determineElementClass(JSONArray jsonArray)
Determines the common class of elements in the givenJSONArray
.static java.lang.String
escape(java.lang.String v)
Escapes a string for JSON formatting.static boolean
isEmpty(JSONArray jsonArray)
Checks if the givenJSONArray
is empty.static boolean
isEmpty(JSONObject jsonObject)
Checks if the givenJSONObject
is empty.static boolean
isJSONArray(java.lang.Object value)
Checks if the given object is an instance ofJSONArray
.static boolean
isJSONObject(java.lang.Object value)
Checks if the given object is an instance ofJSONObject
.static boolean
isNotEmpty(JSONArray jsonArray)
Checks if the givenJSONArray
is not empty.static boolean
isNotEmpty(JSONObject jsonObject)
Checks if the givenJSONObject
is not empty.static boolean
isNotNull(java.lang.Object object)
Checks if the given object is not null and not equal toJSONObject.NULL
.static boolean
isNull(java.lang.Object object)
Checks if the given object is null or equals toJSONObject.NULL
.static JSONArray
jsonArray(java.lang.String json)
Parses a JSON string and returns aJSONArray
representation of it.static JSONObject
jsonObject(java.lang.String json)
Parses a JSON string and returns aJSONObject
representation of it.static int
length(JSONArray jsonArray)
Returns the number of values in the specifiedJSONArray
.static int
length(JSONObject jsonObject)
Returns the number of name/value mappings in the specifiedJSONObject
.static <E> E[]
readArray(JSONArray jsonArray, java.lang.Class<E> componentType)
Reads aJSONArray
and converts it into an array of the specified component type.static <E> E[]
readArray(java.lang.String json, java.lang.Class<E> componentType)
Reads a JSON array string and converts it into an array of the specified component type.static <V> V
readValue(JSONObject jsonObject, java.lang.Class<V> targetType)
Reads aJSONObject
and converts it into an instance of the specified target type.static <V> V
readValue(java.lang.String json, java.lang.Class<V> targetType)
Reads a JSON string and converts it into an instance of the specified target type.static <V> V
readValueAsBean(JSONObject jsonObject, java.lang.Class<V> beanClass)
Reads aJSONObject
and converts it into an instance of the specified bean type.static java.util.Map<java.lang.String,java.lang.Object>
readValueAsMap(JSONObject jsonObject)
static <V> V
readValues(JSONArray jsonArray, java.lang.Class<V> multipleClass, java.lang.Class<?> elementClass)
Reads aJSONArray
and converts it into an instance of the specified collection or array type.static java.lang.Object
readValues(JSONArray jsonArray, java.lang.reflect.Type targetType)
Reads aJSONArray
and converts it into an instance of the specified target type.static <V> V
readValues(java.lang.String json, java.lang.Class<V> multipleClass, java.lang.Class<?> elementClass)
Reads a JSON array string and converts it into an instance of the specified collection or array type.static java.lang.String
writeBeanAsString(java.lang.Object javaBean)
Converts a JavaBean object into its JSON string representation.static java.lang.String
writeValueAsString(java.lang.Object object)
Converts an object into its JSON string representation.
-
-
-
Method Detail
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, boolean value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, byte value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, short value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, int value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, long value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, float value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, double value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, char value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Boolean value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Byte value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Short value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Integer value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Long value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Float value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Double value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Character value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.String value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.reflect.Type value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Object value)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, boolean[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, byte[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, short[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, int[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, long[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, float[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, double[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, char[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.String[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Boolean[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Byte[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Short[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Integer[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Long[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Float[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Double[] values)
-
append
public static void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Character[] values)
-
append
public static <T> void append(java.lang.StringBuilder jsonBuilder, java.lang.String name, T[] values)
-
appendValue
public static void appendValue(java.lang.StringBuilder jsonBuilder, java.lang.Object value)
-
appendName
public static java.lang.StringBuilder appendName(java.lang.StringBuilder jsonBuilder, java.lang.String name)
-
length
public static int length(JSONObject jsonObject)
Returns the number of name/value mappings in the specifiedJSONObject
.This method returns the count of key-value pairs in the given
JSONObject
. If theJSONObject
isnull
, this method returns0
.Example Usage
JSONObject obj = new JSONObject(); obj.put("name", "John"); obj.put("age", 30); int length = JSONUtils.length(obj); // returns 2 JSONObject nullObj = null; int nullLength = JSONUtils.length(nullObj); // returns 0
- Parameters:
jsonObject
- theJSONObject
whose length is to be determined- Returns:
- the number of name/value mappings in the
JSONObject
, or0
if theJSONObject
isnull
- See Also:
JSONObject.length()
-
length
public static int length(JSONArray jsonArray)
Returns the number of values in the specifiedJSONArray
.This method returns the count of elements in the given
JSONArray
. If theJSONArray
isnull
, this method returns0
.Example Usage
JSONArray array = new JSONArray(); array.put("value1"); array.put("value2"); int length = JSONUtils.length(array); // returns 2 JSONArray nullArray = null; int nullLength = JSONUtils.length(nullArray); // returns 0
- Parameters:
jsonArray
- theJSONArray
whose length is to be determined- Returns:
- the number of values in the
JSONArray
, or0
if theJSONArray
isnull
- See Also:
JSONArray.length()
-
isEmpty
public static boolean isEmpty(JSONObject jsonObject)
Checks if the givenJSONObject
is empty.This method returns
true
if the providedJSONObject
isnull
or contains no key-value mappings. Otherwise, it returnsfalse
.Example Usage
JSONObject obj = new JSONObject(); boolean empty = JSONUtils.isEmpty(obj); // returns true obj.put("key", "value"); boolean notEmpty = JSONUtils.isEmpty(obj); // returns false JSONObject nullObj = null; boolean nullEmpty = JSONUtils.isEmpty(nullObj); // returns true
- Parameters:
jsonObject
- theJSONObject
to check- Returns:
true
if theJSONObject
isnull
or empty,false
otherwise- See Also:
length(JSONObject)
,JSONObject.length()
-
isEmpty
public static boolean isEmpty(JSONArray jsonArray)
Checks if the givenJSONArray
is empty.This method returns
true
if the providedJSONArray
isnull
or contains no elements. Otherwise, it returnsfalse
.Example Usage
JSONArray array = new JSONArray(); boolean empty = JSONUtils.isEmpty(array); // returns true array.put("value"); boolean notEmpty = JSONUtils.isEmpty(array); // returns false JSONArray nullArray = null; boolean nullEmpty = JSONUtils.isEmpty(nullArray); // returns true
- Parameters:
jsonArray
- theJSONArray
to check- Returns:
true
if theJSONArray
isnull
or empty,false
otherwise- See Also:
length(JSONArray)
,JSONArray.length()
-
isNotEmpty
public static boolean isNotEmpty(JSONObject jsonObject)
Checks if the givenJSONObject
is not empty.This method returns
true
if the providedJSONObject
is notnull
and contains at least one key-value mapping. Otherwise, it returnsfalse
.Example Usage
JSONObject obj = new JSONObject(); boolean empty = JSONUtils.isNotEmpty(obj); // returns false obj.put("key", "value"); boolean notEmpty = JSONUtils.isNotEmpty(obj); // returns true JSONObject nullObj = null; boolean nullEmpty = JSONUtils.isNotEmpty(nullObj); // returns false
- Parameters:
jsonObject
- theJSONObject
to check- Returns:
true
if theJSONObject
is notnull
and not empty,false
otherwise- See Also:
isEmpty(JSONObject)
,JSONObject.length()
-
isNotEmpty
public static boolean isNotEmpty(JSONArray jsonArray)
Checks if the givenJSONArray
is not empty.This method returns
true
if the providedJSONArray
is notnull
and contains at least one element. Otherwise, it returnsfalse
.Example Usage
JSONArray array = new JSONArray(); boolean empty = JSONUtils.isNotEmpty(array); // returns false array.put("value"); boolean notEmpty = JSONUtils.isNotEmpty(array); // returns true JSONArray nullArray = null; boolean nullEmpty = JSONUtils.isNotEmpty(nullArray); // returns false
- Parameters:
jsonArray
- theJSONArray
to check- Returns:
true
if theJSONArray
is notnull
and not empty,false
otherwise- See Also:
isEmpty(JSONArray)
,JSONArray.length()
-
isNull
public static boolean isNull(java.lang.Object object)
Checks if the given object is null or equals toJSONObject.NULL
.This method returns
true
if the provided object isnull
or is equal toJSONObject.NULL
, which is a special sentinel value used in JSON operations. Otherwise, it returnsfalse
.Example Usage
boolean result1 = JSONUtils.isNull(null); // returns true boolean result2 = JSONUtils.isNull(JSONObject.NULL); // returns true boolean result3 = JSONUtils.isNull("some value"); // returns false
- Parameters:
object
- the object to check- Returns:
true
if the object isnull
or equals toJSONObject.NULL
,false
otherwise- See Also:
JSONObject.NULL
-
isNotNull
public static boolean isNotNull(java.lang.Object object)
Checks if the given object is not null and not equal toJSONObject.NULL
.This method returns
true
if the provided object is neithernull
nor equal toJSONObject.NULL
, which is a special sentinel value used in JSON operations. Otherwise, it returnsfalse
.Example Usage
boolean result1 = JSONUtils.isNotNull("some value"); // returns true boolean result2 = JSONUtils.isNotNull(JSONObject.NULL); // returns false boolean result3 = JSONUtils.isNotNull(null); // returns false
- Parameters:
object
- the object to check- Returns:
true
if the object is notnull
and not equal toJSONObject.NULL
,false
otherwise- See Also:
JSONObject.NULL
,isNull(Object)
-
isJSONObject
public static boolean isJSONObject(java.lang.Object value)
Checks if the given object is an instance ofJSONObject
.This method returns
true
if the provided object is an instance ofJSONObject
, andfalse
otherwise. It is useful for type checking before performing operations specific toJSONObject
.Example Usage
Object obj = new JSONObject(); boolean result = JSONUtils.isJSONObject(obj); // returns true Object str = "not a JSONObject"; boolean result2 = JSONUtils.isJSONObject(str); // returns false
- Parameters:
value
- the object to check- Returns:
true
if the object is an instance ofJSONObject
,false
otherwise- See Also:
JSONObject
-
isJSONArray
public static boolean isJSONArray(java.lang.Object value)
Checks if the given object is an instance ofJSONArray
.This method returns
true
if the provided object is an instance ofJSONArray
, andfalse
otherwise. It is useful for type checking before performing operations specific toJSONArray
.Example Usage
Object obj = new JSONArray(); boolean result = JSONUtils.isJSONArray(obj); // returns true Object str = "not a JSONArray"; boolean result2 = JSONUtils.isJSONArray(str); // returns false
-
jsonObject
@Nonnull public static JSONObject jsonObject(java.lang.String json) throws java.lang.IllegalArgumentException
Parses a JSON string and returns aJSONObject
representation of it.This method takes a valid JSON string and converts it into a
JSONObject
. If the string is not a valid JSON or cannot be parsed into aJSONObject
, anIllegalArgumentException
will be thrown with the underlyingJSONException
as the cause.Example Usage
String jsonString = "{\"name\":\"John\", \"age\":30}"; JSONObject jsonObject = JSONUtils.jsonObject(jsonString); String name = jsonObject.getString("name"); // "John" int age = jsonObject.getInt("age"); // 30 // Invalid JSON example: try { JSONUtils.jsonObject("{invalid json}"); } catch (IllegalArgumentException e) { // Handle parsing error }
- Parameters:
json
- the JSON string to parse- Returns:
- a
JSONObject
representation of the parsed JSON string - Throws:
java.lang.IllegalArgumentException
- if the string is not valid JSON or cannot be parsed
-
jsonArray
@Nonnull public static JSONArray jsonArray(java.lang.String json) throws java.lang.IllegalArgumentException
Parses a JSON string and returns aJSONArray
representation of it.This method takes a valid JSON string and converts it into a
JSONArray
. If the string is not a valid JSON or cannot be parsed into aJSONArray
, anIllegalArgumentException
will be thrown with the underlyingJSONException
as the cause.Example Usage
String jsonString = "[\"apple\", \"banana\", \"cherry\"]"; JSONArray jsonArray = JSONUtils.jsonArray(jsonString); String firstItem = jsonArray.getString(0); // "apple" int length = jsonArray.length(); // 3 // Invalid JSON example: try { JSONUtils.jsonArray("[invalid json]"); } catch (IllegalArgumentException e) { // Handle parsing error }
- Parameters:
json
- the JSON string to parse- Returns:
- a
JSONArray
representation of the parsed JSON string - Throws:
java.lang.IllegalArgumentException
- if the string is not valid JSON or cannot be parsed- See Also:
JSONArray
-
readValue
@Nonnull public static <V> V readValue(java.lang.String json, java.lang.Class<V> targetType)
Reads a JSON string and converts it into an instance of the specified target type.This method parses the provided JSON string into a
JSONObject
and then maps its properties to a new instance of the target type. It supports nested objects, collections, and type conversion where necessary.Example Usage
String json = "{\"name\":\"John Doe\",\"age\":30}"; Person person = JSONUtils.readValue(json, Person.class); // person.getName() returns "John Doe" // person.getAge() returns 30 String nestedJson = "{\"user\":{\"name\":\"Jane\"},\"active\":true}"; MyBean bean = JSONUtils.readValue(nestedJson, MyBean.class); // bean.getUser().getName() returns "Jane" // bean.isActive() returns true
- Type Parameters:
V
- the type of the target object- Parameters:
json
- the JSON string to parse and converttargetType
- the class of the target type to which the JSON should be converted- Returns:
- an instance of the target type populated with data from the JSON string
- Throws:
java.lang.IllegalArgumentException
- if the JSON string is invalid or cannot be converted to the target type- See Also:
JSONObject
,readValue(JSONObject, Class)
-
readValue
@Nonnull public static <V> V readValue(JSONObject jsonObject, java.lang.Class<V> targetType)
Reads aJSONObject
and converts it into an instance of the specified target type.This method takes a
JSONObject
and maps its properties to a new instance of the target type. It supports nested objects, collections, and type conversion where necessary.Example Usage
JSONObject jsonObject = new JSONObject("{\"name\":\"John Doe\",\"age\":30}"); Map<String, Object> map = JSONUtils.readValueAsMap(jsonObject); // map.get("name") returns "John Doe" // map.get("age") returns 30 JSONObject nestedJsonObject = new JSONObject("{\"user\":{\"name\":\"Jane\"},\"active\":true}"); MyBean bean = JSONUtils.readValue(nestedJsonObject, MyBean.class); // bean.getUser().getName() returns "Jane" // bean.isActive() returns true
- Type Parameters:
V
- the type of the target object- Parameters:
jsonObject
- theJSONObject
to parse and converttargetType
- the class of the target type to which the JSON should be converted- Returns:
- an instance of the target type populated with data from the
JSONObject
- Throws:
java.lang.IllegalArgumentException
- if theJSONObject
cannot be converted to the target type- See Also:
JSONObject
,readValue(String, Class)
-
readValueAsMap
public static java.util.Map<java.lang.String,java.lang.Object> readValueAsMap(JSONObject jsonObject)
Reads aJSONObject
and converts it into aMap
withString
keys andObject
values.This method takes a
JSONObject
and maps its properties to a newMap
. Each key-value pair in theJSONObject
is added to the map, with values being converted if necessary.Example Usage
JSONObject jsonObject = new JSONObject("{\"name\":\"John Doe\",\"age\":30}"); Map<String, Object> map = JSONUtils.readValueAsMap(jsonObject); // map.get("name") returns "John Doe" // map.get("age") returns 30 JSONObject nestedJsonObject = new JSONObject("{\"user\":{\"name\":\"Jane\"},\"active\":true}"); Map<String, Object> nestedMap = JSONUtils.readValueAsMap(nestedJsonObject); // nestedMap.get("user") returns a Map representing the user object // nestedMap.get("active") returns true
- Parameters:
jsonObject
- theJSONObject
to parse and convert- Returns:
- a
Map
populated with data from theJSONObject
- See Also:
JSONObject
-
readValueAsBean
@Nonnull public static <V> V readValueAsBean(JSONObject jsonObject, java.lang.Class<V> beanClass)
Reads aJSONObject
and converts it into an instance of the specified bean type.This method takes a
JSONObject
and maps its properties to a new instance of the bean type. It supports nested objects, collections, and type conversion where necessary.Example Usage
JSONObject jsonObject = new JSONObject("{\"name\":\"John Doe\",\"age\":30}"); Person person = JSONUtils.readValue(jsonObject, Person.class); // person.getName() returns "John Doe" // person.getAge() returns 30 JSONObject nestedJsonObject = new JSONObject("{\"user\":{\"name\":\"Jane\"},\"active\":true}"); MyBean bean = JSONUtils.readValue(nestedJsonObject, MyBean.class); // bean.getUser().getName() returns "Jane" // bean.isActive() returns true
- Type Parameters:
V
- the type of the target object- Parameters:
jsonObject
- theJSONObject
to parse and convertbeanClass
- the class of the Bean to which the JSON should be converted- Returns:
- an instance of the bean type populated with data from the
JSONObject
- Throws:
java.lang.IllegalArgumentException
- if theJSONObject
cannot be converted to the bean type- See Also:
JSONObject
,readValue(String, Class)
-
readValues
@Nullable public static <V> V readValues(java.lang.String json, java.lang.Class<V> multipleClass, java.lang.Class<?> elementClass)
Reads a JSON array string and converts it into an instance of the specified collection or array type.This method parses the provided JSON array string into a
JSONArray
and then maps its elements to a new instance of the specified collection or array type. It supports arrays,List
,Set
,Queue
, andEnumeration
.Example Usage
String json = "[\"apple\", \"banana\", \"cherry\"]"; // Convert to String array String[] stringArray = (String[]) JSONUtils.readValues(json, String[].class, String.class); // Convert to List<String> List<String> stringList = (List<String>) JSONUtils.readValues(json, List.class, String.class); // Convert to Set<String> Set<String> stringSet = (Set<String>) JSONUtils.readValues(json, Set.class, String.class);
- Parameters:
json
- the JSON array string to parse and convertmultipleClass
- the class of the target collection or array type to which the JSON should be convertedelementClass
- the class of the elements in the target collection or array- Returns:
- an instance of the target collection or array type populated with data from the JSON array string,
or
null
if the target type is not supported - Throws:
java.lang.IllegalArgumentException
- if the JSON string is invalid or cannot be parsed into aJSONArray
- See Also:
JSONArray
,readValues(JSONArray, Class, Class)
-
readValues
@Nullable public static java.lang.Object readValues(JSONArray jsonArray, java.lang.reflect.Type targetType)
Reads aJSONArray
and converts it into an instance of the specified target type.This method takes a
JSONArray
and maps its elements to a new instance of the specified target type. It supports arrays,List
,Set
,Queue
, andEnumeration
.Example Usage
JSONArray jsonArray = new JSONArray("[\"apple\", \"banana\", \"cherry\"]"); // Convert to String array String[] stringArray = (String[]) JSONUtils.readValues(jsonArray, String[].class); // Convert to List<String> List<String> stringList = (List<String>) JSONUtils.readValues(jsonArray, List.class); // Convert to Set<String> Set<String> stringSet = (Set<String>) JSONUtils.readValues(jsonArray, Set.class);
- Parameters:
jsonArray
- theJSONArray
to parse and converttargetType
- the target type to which the JSON should be converted, it can be an array,List
,Set
,Queue
, orEnumeration
- Returns:
- an instance of the target type populated with data from the
JSONArray
, ornull
if the target type is not supported or theJSONArray
is empty - See Also:
JSONArray
,readValues(JSONArray, Class, Class)
-
readValues
@Nullable public static <V> V readValues(JSONArray jsonArray, java.lang.Class<V> multipleClass, java.lang.Class<?> elementClass)
Reads aJSONArray
and converts it into an instance of the specified collection or array type.This method takes a
JSONArray
and maps its elements to a new instance of the specified collection or array type. It supports arrays,List
,Set
,Queue
, andEnumeration
.Example Usage
JSONArray jsonArray = new JSONArray("[\"apple\", \"banana\", \"cherry\"]"); // Convert to String array String[] stringArray = (String[]) JSONUtils.readValues(jsonArray, String[].class, String.class); // Convert to List<String> List<String> stringList = (List<String>) JSONUtils.readValues(jsonArray, List.class, String.class); // Convert to Set<String> Set<String> stringSet = (Set<String>) JSONUtils.readValues(jsonArray, Set.class, String.class);
- Parameters:
jsonArray
- theJSONArray
to parse and convertmultipleClass
- the class of the target collection or array type to which the JSON should be convertedelementClass
- the class of the elements in the target collection or array- Returns:
- an instance of the target collection or array type populated with data from the
JSONArray
, ornull
if the target type is not supported - See Also:
JSONArray
,readValues(String, Class, Class)
-
readArray
public static <E> E[] readArray(java.lang.String json, java.lang.Class<E> componentType)
Reads a JSON array string and converts it into an array of the specified component type.This method parses the provided JSON array string into a
JSONArray
and then maps its elements to a new array of the specified component type. It supports arrays of any type, including primitives and their wrapper classes.Example Usage
String json = "[\"apple\", \"banana\", \"cherry\"]"; String[] stringArray = JSONUtils.readArray(json, String.class); // stringArray[0] returns "apple" // stringArray.length returns 3 String numberJson = "[1, 2, 3]"; Integer[] integerArray = JSONUtils.readArray(numberJson, Integer.class); // integerArray[0] returns 1 // integerArray.length returns 3
- Type Parameters:
E
- the type of the elements in the array- Parameters:
json
- the JSON array string to parse and convertcomponentType
- the class of the component type of the array- Returns:
- an array of the specified component type populated with data from the JSON array string
- Throws:
java.lang.IllegalArgumentException
- if the JSON string is invalid or cannot be parsed into aJSONArray
- See Also:
JSONArray
,readArray(JSONArray, Class)
-
readArray
public static <E> E[] readArray(JSONArray jsonArray, java.lang.Class<E> componentType)
Reads aJSONArray
and converts it into an array of the specified component type.This method takes a
JSONArray
and maps its elements to a new array of the specified component type. It supports arrays of any type, including primitives and their wrapper classes.Example Usage
JSONArray jsonArray = new JSONArray("[\"apple\", \"banana\", \"cherry\"]"); String[] stringArray = JSONUtils.readArray(jsonArray, String.class); // stringArray[0] returns "apple" // stringArray.length returns 3 JSONArray numberJsonArray = new JSONArray("[1, 2, 3]"); Integer[] integerArray = JSONUtils.readArray(numberJsonArray, Integer.class); // integerArray[0] returns 1 // integerArray.length returns 3
- Type Parameters:
E
- the type of the elements in the array- Parameters:
jsonArray
- theJSONArray
to parse and convertcomponentType
- the class of the component type of the array- Returns:
- an array of the specified component type populated with data from the
JSONArray
- See Also:
JSONArray
,readArray(String, Class)
-
writeValueAsString
@Nullable public static java.lang.String writeValueAsString(java.lang.Object object)
Converts an object into its JSON string representation.This method takes an object, wraps it using
JSONObject.wrap(Object)
, and then converts it to a JSON string if it is aJSONObject
orJSONArray
.Example Usage
String jsonString = JSONUtils.writeValueAsString(Map.of("name", "John", "age", 30)); // Result: {"name":"John","age":30} String arrayJson = JSONUtils.writeValueAsString(new String[]{"apple", "banana"}); // Result: ["apple","banana"]
- Parameters:
object
- the object to be converted to a JSON string.- Returns:
- a JSON string representation of the given object, or
null
if conversion is not possible. - See Also:
JSONObject.wrap(Object)
-
writeBeanAsString
@Nonnull public static java.lang.String writeBeanAsString(java.lang.Object javaBean)
Converts a JavaBean object into its JSON string representation.This method takes a JavaBean object, resolves its properties into a map, and then constructs a
JSONObject
from that map. The resulting JSON object is then converted to a string.Example Usage
public class Person { private String name; private int age; // Getters and setters... } Person person = new Person(); person.setName("John Doe"); person.setAge(30); String jsonString = JSONUtils.writeJavaBeanAsString(person); // Result: {"name":"John Doe","age":30}
- Parameters:
javaBean
- the JavaBean object to be converted to a JSON string.- Returns:
- a JSON string representation of the given JavaBean.
- Throws:
java.lang.IllegalArgumentException
- if the input object is null.
-
determineElementClass
@Nonnull public static java.lang.Class<?> determineElementClass(JSONArray jsonArray)
Determines the common class of elements in the givenJSONArray
.This method iterates through the elements of the provided
JSONArray
to find a common class. If all elements are of the same class or one class is assignable from all others, that class is returned. If no common class can be determined,Object.class
is returned.Example Usage
JSONArray array1 = new JSONArray("[\"apple\", \"banana\", \"cherry\"]"); Class<?> commonClass1 = JSONUtils.determineElementClass(array1); // returns String.class JSONArray array2 = new JSONArray("[1, \"banana\", 3.14]"); Class<?> commonClass2 = JSONUtils.determineElementClass(array2); // returns Object.class JSONArray array3 = new JSONArray("[1, 2, 3]"); Class<?> commonClass3 = JSONUtils.determineElementClass(array3); // returns Integer.class
- Parameters:
jsonArray
- theJSONArray
whose elements' common class is to be determined- Returns:
- the common class of the elements, or
Object.class
if no common class can be determined
-
escape
public static java.lang.String escape(@Nullable java.lang.String v)
Escapes a string for JSON formatting.This method takes a string and escapes characters that are not allowed in JSON strings, such as quotation marks, reverse solidus, and control characters (U+0000 through U+001F). It also escapes ' ' and ' ', which JavaScript interprets as newline characters.
Example Usage
String escaped = JSONUtils.escape("Hello\nWorld"); // returns "Hello\\nWorld" String escaped2 = JSONUtils.escape("Quote: \"Hello\""); // returns "Quote: \\\"Hello\\\"" String escaped3 = JSONUtils.escape("Backslash: \\"); // returns "Backslash: \\\\"
- Parameters:
v
- the string to escape, may benull
- Returns:
- the escaped string, or an empty string if the input is
null
-
-