net.sf.json.util 包


net.sf.json.util
Class JSONUtils

java.lang.Object
  net.sf.json.util.JSONUtils

public final class JSONUtils
extends Object
 

Provides useful methods on java objects and JSON values.

Version:
7
Author:
Andres Almiray

Field Summary
staticString DOUBLE_QUOTE Constant for char "
staticString SINGLE_QUOTE Constant for char '
Method Summary
staticString convertToJavaIdentifier(Stringkey) Transforms the string into a valid Java Identifier. The default strategy is JavaIdentifierTransformer.NOOP
staticString convertToJavaIdentifier(Stringkey, JsonConfigjsonConfig) Transforms the string into a valid Java Identifier. The default strategy is JavaIdentifierTransformer.NOOP
staticString doubleToString(doubled) Produce a string from a double.
staticString getFunctionBody(Stringfunction) Returns the body of a function literal.
staticString getFunctionParams(Stringfunction) Returns the params of a function literal.
staticClass getInnerComponentType(Classtype) Returns the inner-most component type of an Array.
staticMorpherRegistry getMorpherRegistry() Returns the singleton MorpherRegistry.
staticMap getProperties(JSONObjectjsonObject) Creates a Map with all the properties of the JSONObject.
staticClass getTypeClass(Objectobj) Returns the JSON type. Values are Object, String, Boolean, Number(subclasses) & JSONFunction.
staticint hashCode(Objectvalue) Returns the hashcode of value. If null it will return JSONNull.getInstance().hashCode(). If value is JSON, JSONFunction or String, value.hashCode is returned, otherwise the value is transformed to a String an its hashcode is returned.
staticboolean hasQuotes(Stringinput) Returns true if the input has single-quotes or double-quotes at both sides.
staticboolean isArray(Classclazz) Tests if a Class represents an array or Collection.
staticboolean isArray(Objectobj) Tests if obj is an array or Collection.
staticboolean isBoolean(Classclazz) Tests if Class represents a Boolean or primitive boolean
staticboolean isBoolean(Objectobj) Tests if obj is a Boolean or primitive boolean
staticboolean isDouble(Classclazz) Tests if Class represents a primitive double or wrapper.
staticboolean isFunction(Objectobj) Tests if obj is javaScript function. Obj must be a non-null String and match "^function[ ]?\\(.\*\)[ ]?\\{.\*\}$"
staticboolean isFunctionHeader(Objectobj) Tests if obj is javaScript function header. Obj must be a non-null String and match "^function[ ]?\\(.\*\)$"
staticboolean isJavaIdentifier(Stringstr) Returns trus if str represents a valid Java identifier.
staticboolean isJsonKeyword(Stringinput, JsonConfigjsonConfig)
staticboolean isNull(Objectobj) Tests if the obj is a javaScript null.
staticboolean isNumber(Classclazz) Tests if Class represents a primitive number or wrapper.
staticboolean isNumber(Objectobj) Tests if obj is a primitive number or wrapper.
staticboolean isObject(Objectobj) Tests if obj is not a boolean, number, string or array.
staticboolean isString(Classclazz) Tests if Class represents a String or a char
staticboolean isString(Objectobj) Tests if obj is a String or a char
staticboolean mayBeJSON(Stringstring) Tests if the String possibly represents a valid JSON String. Valid JSON strings are: "null" starts with "[" and ends with "]" starts with "{" and ends with "}"
staticDynaBean newDynaBean(JSONObjectjsonObject) Creates a new MorphDynaBean from a JSONObject.
staticDynaBean newDynaBean(JSONObjectjsonObject, JsonConfigjsonConfig) Creates a new MorphDynaBean from a JSONObject.
staticString numberToString(Numbern) Produce a string from a Number.
staticString quote(Stringstring) Produce a string in double quotes with backslash sequences in all the right places.
staticString stripQuotes(Stringinput) Strips any single-quotes or double-quotes from both sides of the string.
staticvoid testValidity(Objecto) Throw an exception if the object is an NaN or infinite number.
staticNumber transformNumber(Numberinput) Transforms a Number into a valid javascript number. Float gets promoted to Double. Byte and Short get promoted to Integer. Long gets downgraded to Integer if possible.
staticString valueToString(Objectvalue) Make a JSON text of an Object value.
staticString valueToString(Objectvalue, intindentFactor, intindent) Make a prettyprinted JSON text of an object value.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

DOUBLE_QUOTE

public static final String DOUBLE_QUOTE
Constant for char "

See Also:
Constant Field Values


SINGLE_QUOTE

public static final String SINGLE_QUOTE
Constant for char '

See Also:
Constant Field Values

Method Detail

convertToJavaIdentifier

public static String convertToJavaIdentifier(Stringkey)
Transforms the string into a valid Java Identifier.
The default strategy is JavaIdentifierTransformer.NOOP

Throws:
JSONException - if the string can not be transformed.

convertToJavaIdentifier

public static String convertToJavaIdentifier(Stringkey,
                                             JsonConfigjsonConfig)
Transforms the string into a valid Java Identifier.
The default strategy is JavaIdentifierTransformer.NOOP

Throws:
JSONException - if the string can not be transformed.

doubleToString

public static String doubleToString(doubled)
Produce a string from a double. The string "null" will be returned if the number is not finite.

Parameters:
d - A double.
Returns:
A String.

getFunctionBody

public static String getFunctionBody(Stringfunction)
Returns the body of a function literal.


getFunctionParams

public static String getFunctionParams(Stringfunction)
Returns the params of a function literal.


getInnerComponentType

public static Class getInnerComponentType(Classtype)
Returns the inner-most component type of an Array.


getMorpherRegistry

public static MorpherRegistry getMorpherRegistry()
Returns the singleton MorpherRegistry.


getProperties

public static Map getProperties(JSONObjectjsonObject)
Creates a Map with all the properties of the JSONObject.


getTypeClass

public static Class getTypeClass(Objectobj)
Returns the JSON type.
Values are Object, String, Boolean, Number(subclasses) & JSONFunction.


hashCode

public static int hashCode(Objectvalue)
Returns the hashcode of value.
If null it will return JSONNull.getInstance().hashCode().
If value is JSON, JSONFunction or String, value.hashCode is returned, otherwise the value is transformed to a String an its hashcode is returned.


isArray

public static boolean isArray(Classclazz)
Tests if a Class represents an array or Collection.


isArray

public static boolean isArray(Objectobj)
Tests if obj is an array or Collection.


isBoolean

public static boolean isBoolean(Classclazz)
Tests if Class represents a Boolean or primitive boolean


isBoolean

public static boolean isBoolean(Objectobj)
Tests if obj is a Boolean or primitive boolean


isDouble

public static boolean isDouble(Classclazz)
Tests if Class represents a primitive double or wrapper.


isFunction

public static boolean isFunction(Objectobj)
Tests if obj is javaScript function.
Obj must be a non-null String and match "^function[ ]?\\(.\*\)[ ]?\\{.\*\}$"


isFunctionHeader

public static boolean isFunctionHeader(Objectobj)
Tests if obj is javaScript function header.
Obj must be a non-null String and match "^function[ ]?\\(.\*\)$"


isJavaIdentifier

public static boolean isJavaIdentifier(Stringstr)
Returns trus if str represents a valid Java identifier.


isNull

public static boolean isNull(Objectobj)
Tests if the obj is a javaScript null.


isNumber

public static boolean isNumber(Classclazz)
Tests if Class represents a primitive number or wrapper.


isNumber

public static boolean isNumber(Objectobj)
Tests if obj is a primitive number or wrapper.


isObject

public static boolean isObject(Objectobj)
Tests if obj is not a boolean, number, string or array.


isString

public static boolean isString(Classclazz)
Tests if Class represents a String or a char


isString

public static boolean isString(Objectobj)
Tests if obj is a String or a char


mayBeJSON

public static boolean mayBeJSON(Stringstring)
Tests if the String possibly represents a valid JSON String.
Valid JSON strings are:
  • "null"
  • starts with "[" and ends with "]"
  • starts with "{" and ends with "}"


newDynaBean

public static DynaBean newDynaBean(JSONObjectjsonObject)
Creates a new MorphDynaBean from a JSONObject. The MorphDynaBean will have all the properties of the original JSONObject with the most accurate type. Values of properties are not copied.


newDynaBean

public static DynaBean newDynaBean(JSONObjectjsonObject,
                                   JsonConfigjsonConfig)
Creates a new MorphDynaBean from a JSONObject. The MorphDynaBean will have all the properties of the original JSONObject with the most accurate type. Values of properties are not copied.


numberToString

public static String numberToString(Numbern)
Produce a string from a Number.

Parameters:
n - A Number
Returns:
A String.
Throws:
JSONException - If n is a non-finite number.

quote

public static String quote(Stringstring)
Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted within </, allowing text to be delivered in HTML. In JSON text, string cannot contain a control character an unescaped or backslash.
CAUTION: if string represents a javascript function, translation of characters will not take place. This will produce a non-conformant JSON text.

Parameters:
string - A String
Returns:
A String correctly formatted for insertion in a JSON text.

stripQuotes

public static String stripQuotes(Stringinput)
Strips any single-quotes or double-quotes from both sides of the string.


hasQuotes

public static boolean hasQuotes(Stringinput)
Returns true if the input has single-quotes or double-quotes at both sides.


isJsonKeyword

public static boolean isJsonKeyword(Stringinput,
                                    JsonConfigjsonConfig)

testValidity

public static void testValidity(Objecto)
Throw an exception if the object is an NaN or infinite number.

Parameters:
o - The object to test.
Throws:
JSONException - If o is a non-finite number.

transformNumber

public static Number transformNumber(Numberinput)
Transforms a Number into a valid javascript number.
Float gets promoted to Double.
Byte and Short get promoted to Integer.
Long gets downgraded to Integer if possible.


valueToString

public static String valueToString(Objectvalue)
Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does not contain a toJSONString method (which is the most common case), then a text will be produced by the rules.

Warning: This method assumes that the data structure is acyclical.

Parameters:
value - The value to be serialized.
Returns:
a printable, displayable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
Throws:
JSONException - If the value is or contains an invalid number.

valueToString

public static String valueToString(Objectvalue,
                                   intindentFactor,
                                   intindent)
Make a prettyprinted JSON text of an object value.

Warning: This method assumes that the data structure is acyclical.

Parameters:
value - The value to be serialized.
indentFactor - The number of spaces to add to each level of indentation.
indent - The indentation of the top level.
Returns:
a printable, displayable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).
Throws:
JSONException - If the object contains an invalid number.


这个错误是因为你尝试将一个 `java.util.LinkedHashMap` 类型的对象转换成 `net.sf.json.JSON` 类型,造成了类型转换错误。 通常情况下,将一个对象转换成 JSON 格式的字符串,可以使用 `net.sf.json.JSONObject` 或 `net.sf.json.JSONArray` 类来操作,它们提供了丰富的方法来构建和操作 JSON 对象和数组。 你可以试试下面的代码,使用 `JSONObject` 将 `java.util.LinkedHashMap` 类型的对象转换成 JSON 字符串: ```java import net.sf.json.JSONObject; import java.util.LinkedHashMap; import java.util.Map; public class Demo { public static void main(String[] args) { Map<String, Object> map = new LinkedHashMap<>(); map.put("name", "张三"); map.put("age", 18); JSONObject json = JSONObject.fromObject(map); System.out.println(json.toString()); } } ``` 在上面的代码中,我们先使用 `LinkedHashMap` 创建了一个 Map 对象,然后使用 `JSONObject.fromObject()` 方法将其转换成 JSON 对象,并使用 `toString()` 方法将其转换成 JSON 字符串。 输出结果为: ``` {"name":"张三","age":18} ``` 如果你需要将一个含多个键值对的对象转换成 JSON 字符串,可以使用 `JSONArray`,例如: ```java import net.sf.json.JSONArray; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class Demo { public static void main(String[] args) { List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map1 = new LinkedHashMap<>(); map1.put("name", "张三"); map1.put("age", 18); Map<String, Object> map2 = new LinkedHashMap<>(); map2.put("name", "李四"); map2.put("age", 20); list.add(map1); list.add(map2); JSONArray json = JSONArray.fromObject(list); System.out.println(json.toString()); } } ``` 在上面的代码中,我们创建了一个含两个 `Map` 对象的列表,然后使用 `JSONArray.fromObject()` 方法将其转换成 JSON 数组,并使用 `toString()` 方法将其转换成 JSON 字符串。 输出结果为: ``` [{"name":"张三","age":18},{"name":"李四","age":20}] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值