-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere json JSONObject
Type: Class | Module: microsphere-java-core | Package: io.microsphere.json
Source:
microsphere-java-core/src/main/java/io/microsphere/json/JSONObject.java
A modifiable set of name/value mappings. Names are unique, non-null strings. Values may
be any mix of JSONObject JSONObjects, JSONArray JSONArrays, Strings,
Booleans, Integers, Longs, Doubles, or the special sentinel value #NULL.
This class provides methods to store and retrieve values by their associated names, with support for type coercion when accessing values. It also includes functionality for converting the object to and from JSON formatted strings.
`// Creating a new JSONObject and adding key-value pairs
JSONObject obj = new JSONObject();
obj.put("name", "Alice");
obj.put("age", 30);
// Retrieving values
String name = obj.getString("name"); // returns "Alice"
int age = obj.getInt("age"); // returns 30
// Using opt methods to provide default values
boolean isMember = obj.optBoolean("isMember", false); // returns false if not present
// Converting to JSON string
String jsonStr = obj.toString(); // {"name":"Alice","age":30`
// Parsing from JSON string
String inputJson = "{\"city\":\"New York\",\"population\":8175133}";
JSONObject parsedObj = new JSONObject(inputJson);
String city = parsedObj.getString("city"); // "New York"
}
public class JSONObject-
Introduced in:
0.1.10-SNAPSHOT(current) -
Current Project Version:
0.1.10-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 8 | ✅ Compatible |
| Java 11 | ✅ Compatible |
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
// Creating a new JSONObject and adding key-value pairs
JSONObject obj = new JSONObject();
obj.put("name", "Alice");
obj.put("age", 30);
// Retrieving values
String name = obj.getString("name"); // returns "Alice"
int age = obj.getInt("age"); // returns 30
// Using opt methods to provide default values
boolean isMember = obj.optBoolean("isMember", false); // returns false if not present
// Converting to JSON string
String jsonStr = obj.toString(); // {"name":"Alice","age":30}
// Parsing from JSON string
String inputJson = "{\"city\":\"New York\",\"population\":8175133}";
JSONObject parsedObj = new JSONObject(inputJson);
String city = parsedObj.getString("city"); // "New York"Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-java-core</artifactId>
<version>${microsphere-java.version}</version>
</dependency>Tip: Use the BOM (
microsphere-java-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.json.JSONObject;| Method | Description |
|---|---|
length |
A sentinel value used to explicitly define a name with no value. Unlike |
put |
Maps name to value, clobbering any existing name/value mapping with |
put |
Maps name to value, clobbering any existing name/value mapping with |
put |
Maps name to value, clobbering any existing name/value mapping with |
put |
Maps name to value, clobbering any existing name/value mapping with |
put |
Maps name to value, clobbering any existing name/value mapping with |
putOpt |
Equivalent to put(name, value) when both parameters are non-null; does |
accumulate |
Appends value to the array already mapped to name. If this object |
remove |
Removes the named mapping if it exists; does nothing otherwise. |
isNull |
Returns true if this object has no mapping for name or if it has a mapping |
has |
Returns true if this object has a mapping for name. The mapping may be |
get |
Returns the value mapped by name. |
opt |
Returns the value mapped by name, or null if no such mapping exists. |
getBoolean |
Returns the value mapped by name if it exists and is a boolean or can be |
optBoolean |
Returns the value mapped by name if it exists and is a boolean or can be |
optBoolean |
Returns the value mapped by name if it exists and is a boolean or can be |
getDouble |
Returns the value mapped by name if it exists and is a double or can be |
optDouble |
Returns the value mapped by name if it exists and is a double or can be |
optDouble |
Returns the value mapped by name if it exists and is a double or can be |
getInt |
Returns the value mapped by name if it exists and is an int or can be |
public int length()A sentinel value used to explicitly define a name with no value. Unlike
null, names with this value:
- show up in the
#namesarray - show up in the
#keysiterator - return
truefor#has(String) - do not throw on
#get(String) - are included in the encoded JSON string.
This value violates the general contract of Object#equals by returning true
when compared to null. Its #toString method returns "null".
/
public static final Object NULL = new Object() {
public JSONObject put(String name, boolean value)Maps name to value, clobbering any existing name/value mapping with
the same name.
public JSONObject put(String name, double value)Maps name to value, clobbering any existing name/value mapping with
the same name.
public JSONObject put(String name, int value)Maps name to value, clobbering any existing name/value mapping with
the same name.
public JSONObject put(String name, long value)Maps name to value, clobbering any existing name/value mapping with
the same name.
public JSONObject put(String name, Object value)Maps name to value, clobbering any existing name/value mapping with
the same name. If the value is null, any existing mapping for name
is removed.
public JSONObject putOpt(String name, Object value)Equivalent to put(name, value) when both parameters are non-null; does
nothing otherwise.
public JSONObject accumulate(String name, Object value)Appends value to the array already mapped to name. If this object
has no mapping for name, this inserts a new mapping. If the mapping exists
but its value is not an array, the existing and new values are inserted in order
into a new array which is itself mapped to name. In aggregate, this allows
values to be added to a mapping one at a time.
public Object remove(String name)Removes the named mapping if it exists; does nothing otherwise.
public boolean isNull(String name)Returns true if this object has no mapping for name or if it has a mapping
whose value is #NULL.
public boolean has(String name)Returns true if this object has a mapping for name. The mapping may be
#NULL.
public Object opt(String name)Returns the value mapped by name, or null if no such mapping exists.
public boolean getBoolean(String name)Returns the value mapped by name if it exists and is a boolean or can be
coerced to a boolean.
public boolean optBoolean(String name)Returns the value mapped by name if it exists and is a boolean or can be
coerced to a boolean. Returns false otherwise.
public boolean optBoolean(String name, boolean fallback)Returns the value mapped by name if it exists and is a boolean or can be
coerced to a boolean. Returns fallback otherwise.
public double getDouble(String name)Returns the value mapped by name if it exists and is a double or can be
coerced to a double.
public double optDouble(String name)Returns the value mapped by name if it exists and is a double or can be
coerced to a double. Returns NaN otherwise.
public double optDouble(String name, double fallback)Returns the value mapped by name if it exists and is a double or can be
coerced to a double. Returns fallback otherwise.
public int getInt(String name)Returns the value mapped by name if it exists and is an int or can be
coerced to an int.
JSONArrayJSONTokener
This documentation was auto-generated from the source code of microsphere-java.
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- ByteArrayToObjectConverter
- CharSequenceComparator
- CharSequenceUtils
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
jdk-tools
lang-model
- AnnotatedElementJSONElementVisitor
- AnnotationUtils
- ClassUtils
- ConstructorUtils
- ElementUtils
- ExecutableElementComparator
- FieldUtils
- JSONAnnotationValueVisitor
- JSONElementVisitor
- LoggerUtils
- MemberUtils
- MessagerUtils
- MethodUtils
- ResolvableAnnotationValueVisitor
- StringAnnotationValue
- TypeUtils
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl