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 voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, boolean value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, boolean[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, byte value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, byte[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, char value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, char[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, double value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, double[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, float value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, float[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, int value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, int[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, long value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, long[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, short value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, short[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Boolean value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Boolean[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Byte value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Byte[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Character value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Character[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Double value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Double[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Float value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Float[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Integer value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Integer[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Long value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Long[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Object value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.reflect.Type value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Short value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.Short[] values)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.String value)static voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, java.lang.String[] values)static <T> voidappend(java.lang.StringBuilder jsonBuilder, java.lang.String name, T[] values)static java.lang.StringBuilderappendName(java.lang.StringBuilder jsonBuilder, java.lang.String name)static voidappendValue(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.Stringescape(java.lang.String v)Escapes a string for JSON formatting.static booleanisEmpty(JSONArray jsonArray)Checks if the givenJSONArrayis empty.static booleanisEmpty(JSONObject jsonObject)Checks if the givenJSONObjectis empty.static booleanisJSONArray(java.lang.Object value)Checks if the given object is an instance ofJSONArray.static booleanisJSONObject(java.lang.Object value)Checks if the given object is an instance ofJSONObject.static booleanisNotEmpty(JSONArray jsonArray)Checks if the givenJSONArrayis not empty.static booleanisNotEmpty(JSONObject jsonObject)Checks if the givenJSONObjectis not empty.static booleanisNotNull(java.lang.Object object)Checks if the given object is not null and not equal toJSONObject.NULL.static booleanisNull(java.lang.Object object)Checks if the given object is null or equals toJSONObject.NULL.static JSONArrayjsonArray(java.lang.String json)Parses a JSON string and returns aJSONArrayrepresentation of it.static JSONObjectjsonObject(java.lang.String json)Parses a JSON string and returns aJSONObjectrepresentation of it.static intlength(JSONArray jsonArray)Returns the number of values in the specifiedJSONArray.static intlength(JSONObject jsonObject)Returns the number of name/value mappings in the specifiedJSONObject.static <E> E[]readArray(JSONArray jsonArray, java.lang.Class<E> componentType)Reads aJSONArrayand 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> VreadValue(JSONObject jsonObject, java.lang.Class<V> targetType)Reads aJSONObjectand converts it into an instance of the specified target type.static <V> VreadValue(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> VreadValueAsBean(JSONObject jsonObject, java.lang.Class<V> beanClass)Reads aJSONObjectand 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> VreadValues(JSONArray jsonArray, java.lang.Class<V> multipleClass, java.lang.Class<?> elementClass)Reads aJSONArrayand converts it into an instance of the specified collection or array type.static java.lang.ObjectreadValues(JSONArray jsonArray, java.lang.reflect.Type targetType)Reads aJSONArrayand converts it into an instance of the specified target type.static <V> VreadValues(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.StringwriteBeanAsString(java.lang.Object javaBean)Converts a JavaBean object into its JSON string representation.static java.lang.StringwriteValueAsString(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 theJSONObjectisnull, 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- theJSONObjectwhose length is to be determined- Returns:
- the number of name/value mappings in the
JSONObject, or0if theJSONObjectisnull - 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 theJSONArrayisnull, 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- theJSONArraywhose length is to be determined- Returns:
- the number of values in the
JSONArray, or0if theJSONArrayisnull - See Also:
JSONArray.length()
-
isEmpty
public static boolean isEmpty(JSONObject jsonObject)
Checks if the givenJSONObjectis empty.This method returns
trueif the providedJSONObjectisnullor 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- theJSONObjectto check- Returns:
trueif theJSONObjectisnullor empty,falseotherwise- See Also:
length(JSONObject),JSONObject.length()
-
isEmpty
public static boolean isEmpty(JSONArray jsonArray)
Checks if the givenJSONArrayis empty.This method returns
trueif the providedJSONArrayisnullor 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- theJSONArrayto check- Returns:
trueif theJSONArrayisnullor empty,falseotherwise- See Also:
length(JSONArray),JSONArray.length()
-
isNotEmpty
public static boolean isNotEmpty(JSONObject jsonObject)
Checks if the givenJSONObjectis not empty.This method returns
trueif the providedJSONObjectis notnulland 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- theJSONObjectto check- Returns:
trueif theJSONObjectis notnulland not empty,falseotherwise- See Also:
isEmpty(JSONObject),JSONObject.length()
-
isNotEmpty
public static boolean isNotEmpty(JSONArray jsonArray)
Checks if the givenJSONArrayis not empty.This method returns
trueif the providedJSONArrayis notnulland 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- theJSONArrayto check- Returns:
trueif theJSONArrayis notnulland not empty,falseotherwise- 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
trueif the provided object isnullor 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:
trueif the object isnullor equals toJSONObject.NULL,falseotherwise- 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
trueif the provided object is neithernullnor 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:
trueif the object is notnulland not equal toJSONObject.NULL,falseotherwise- 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
trueif the provided object is an instance ofJSONObject, andfalseotherwise. 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:
trueif the object is an instance ofJSONObject,falseotherwise- See Also:
JSONObject
-
isJSONArray
public static boolean isJSONArray(java.lang.Object value)
Checks if the given object is an instance ofJSONArray.This method returns
trueif the provided object is an instance ofJSONArray, andfalseotherwise. 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 aJSONObjectrepresentation 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, anIllegalArgumentExceptionwill be thrown with the underlyingJSONExceptionas 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
JSONObjectrepresentation 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 aJSONArrayrepresentation 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, anIllegalArgumentExceptionwill be thrown with the underlyingJSONExceptionas 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
JSONArrayrepresentation 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
JSONObjectand 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 aJSONObjectand converts it into an instance of the specified target type.This method takes a
JSONObjectand 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- theJSONObjectto 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 theJSONObjectcannot 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 aJSONObjectand converts it into aMapwithStringkeys andObjectvalues.This method takes a
JSONObjectand maps its properties to a newMap. Each key-value pair in theJSONObjectis 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- theJSONObjectto parse and convert- Returns:
- a
Mappopulated with data from theJSONObject - See Also:
JSONObject
-
readValueAsBean
@Nonnull public static <V> V readValueAsBean(JSONObject jsonObject, java.lang.Class<V> beanClass)
Reads aJSONObjectand converts it into an instance of the specified bean type.This method takes a
JSONObjectand 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- theJSONObjectto 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 theJSONObjectcannot 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
JSONArrayand 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
nullif 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 aJSONArrayand converts it into an instance of the specified target type.This method takes a
JSONArrayand 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- theJSONArrayto 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, ornullif the target type is not supported or theJSONArrayis 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 aJSONArrayand converts it into an instance of the specified collection or array type.This method takes a
JSONArrayand 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- theJSONArrayto 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, ornullif 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
JSONArrayand 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 aJSONArrayand converts it into an array of the specified component type.This method takes a
JSONArrayand 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- theJSONArrayto 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 aJSONObjectorJSONArray.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
nullif 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
JSONObjectfrom 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
JSONArrayto 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.classis 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- theJSONArraywhose elements' common class is to be determined- Returns:
- the common class of the elements, or
Object.classif 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
-
-