├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main └── java │ └── org │ └── andrejs │ └── json │ ├── Json.java │ ├── JsonFactory.java │ ├── JsonSerializer.java │ ├── MapBindings.java │ └── MapOps.java └── test └── java └── org └── andrejs └── json ├── JsonFactoryTest.java ├── JsonScriptingTest.java └── JsonTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # IDE 4 | .project 5 | .settings 6 | .classpath 7 | bin/ 8 | *.iml 9 | 10 | # build 11 | .gradle 12 | build/ 13 | 14 | # Package Files # 15 | *.jar 16 | *.war 17 | *.ear 18 | 19 | # jvm crash logs 20 | hs_err_pid* 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Andrejs Jermakovics 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this library except in compliance with the License. 4 | You may obtain a copy of the License at 5 | 6 | [www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 7 | 8 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CircleCI](https://circleci.com/gh/ajermakovics/json.svg?style=svg)](https://circleci.com/gh/ajermakovics/json) [![](https://jitpack.io/v/org.andrejs/json.svg)](https://jitpack.io/#org.andrejs/json) 2 | 3 | # Json 4 | 5 | Convenience library for handling JSON objects in Java. Goals: 6 | 7 | - Usability 8 | - Minimise verbosity 9 | - Play well with Nashorn JavaScript engine from Java 8 10 | 11 | In essence `Json` is just a thin wrapper around a `Map` where properties are stored. There are lots of functions to manipulate a `Map` such as in Guava or Apache Commons, and you should be able to re-use them. Additional `Map` utilities are provided here. 12 | 13 | ```java 14 | Json addr = new Json() { 15 | String host = "localhost"; 16 | int port = 80; 17 | }; 18 | 19 | addr.toString(); // {"host": "localhost", "port": 80} 20 | addr.set("path", "/").set("proto", "http"); 21 | addr.get("port"); // 80 22 | ``` 23 | 24 | See tests for more examples. 25 | 26 | ## Features 27 | 28 | - Simple and convenient constructors 29 | - Implements `Map` interface so you can treat it like a Map of Maps 30 | - JDK8 Nashorn compatible - use it in JavaScript functions 31 | - Convenience methods for building and getting values 32 | - Serialize to/from String 33 | - Access properties without explicit casting 34 | - Provides `equals`/`hashCode`, so you can store Json in collections 35 | 36 | ## Download 37 | 38 | Grab it from [JitPack](https://jitpack.io/#org.andrejs/json) 39 | 40 | Json depends on Jackson 41 | 42 | ## Constructors 43 | 44 | ```java 45 | new Json("{port: 80}"); // from string. quotes around field names are optional. 46 | new Json( hashMap ); // from map 47 | new Json("port", 80); // key-value 48 | new Json() { int port = 80; } // from fields 49 | new Json("{port: 80} // listen port"); // comments are allowed 50 | ``` 51 | 52 | ## Factory methods 53 | 54 | ```java 55 | Json json = Json.of.url("https://status.github.com/api/status.json"); // download from url 56 | Json json = Json.of.bytes(byteArray); 57 | Json json = Json.of.file("/path/to/file.json"); 58 | Json json = Json.of.bean(beanObject); 59 | Json json = Json.of.string("{port: 80}"); 60 | Json json = Json.of.keyVal("port" 80, "host", "localhost"); // key-value pairs 61 | Json json = Json.of.stream(inputStream); 62 | ``` 63 | 64 | ## Operations 65 | 66 | ```java 67 | Json json = new Json().set("port", 80) 68 | .set("host", "localhost"); // chain calls 69 | 70 | int port = json.get("port", 0); // get or return default. avoid casting 71 | 72 | Json nested = json.at("path", "to", "nested"); // json.path.to.nested 73 | 74 | json.merge( anotherJson ); // merge values recursively 75 | 76 | json.copy(); // deep copy 77 | ``` 78 | 79 | As well as all the methods from `Map`: 80 | 81 | - isEmpty(), keySet(), containsKey(), entrySet(), ... 82 | 83 | ## Scripting usage 84 | 85 | You can pass `Json` to Nashorn JavaScript functions and treat it like a native JSON object: 86 | 87 | ```java 88 | Json addr = new Json("port", 80); 89 | 90 | scriptEngine.eval("function nextPort(addr) { addr.port++; }"); 91 | 92 | invocable.invokeFunction("nextPort", addr); 93 | 94 | out.println( addr.get("port") ); // 81 95 | ``` 96 | 97 | ## Build 98 | 99 | `./gradlew jar` 100 | 101 | Note: running tests requires JDK 8 due to Nashorn tests. 102 | 103 | ## License 104 | 105 | Apache 2.0 106 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | dependencies { 6 | classpath 'org.ajoberstar:grgit:1.4.+' 7 | } 8 | } 9 | ext { 10 | git = org.ajoberstar.grgit.Grgit.open() 11 | } 12 | 13 | apply plugin: 'java' 14 | apply plugin: 'maven' 15 | 16 | sourceCompatibility = 1.8 17 | targetCompatibility = 1.8 18 | 19 | version ext.git.describe() ?: 'dev' 20 | group = 'org.andrejs' 21 | archivesBaseName = "json" 22 | jar.baseName = archivesBaseName 23 | 24 | buildscript { 25 | repositories { 26 | jcenter() 27 | } 28 | } 29 | 30 | jar { 31 | manifest { 32 | attributes 'Implementation-Title': 'Json', 'Implementation-Version': version 33 | } 34 | } 35 | 36 | repositories { 37 | mavenCentral() 38 | } 39 | 40 | dependencies { 41 | compile 'com.fasterxml.jackson.core:jackson-databind:2.7.1' 42 | testCompile 'junit:junit:4.11' 43 | } 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ajermakovics/json/13e49ceeaba997ca2c4f78569e75fb2e12248ce3/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Feb 01 16:07:51 GMT 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/org/andrejs/json/Json.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import java.lang.reflect.Field; 4 | import java.util.LinkedHashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import static java.lang.reflect.Modifier.isStatic; 9 | import static java.util.stream.Collectors.toList; 10 | 11 | /** JSON Object **/ 12 | public class Json extends MapBindings { 13 | 14 | /** Empty Json object. Immutable **/ 15 | public static final Json EMPTY = new Json(MapOps.EMPTY_MAP); 16 | public static JsonFactory of = new JsonFactory(); 17 | 18 | /** Map where all the properties are stored. Nested Json objects are stored as Maps **/ 19 | Map map; 20 | 21 | /** Construct empty JSON Object **/ 22 | public Json() { 23 | } 24 | 25 | /** Construct a JSON Object by parsing a string **/ 26 | public Json(String jsonString) { 27 | map = JsonSerializer.parse(jsonString); 28 | } 29 | 30 | /** Construct a JSON Object from a map. Also usable as a copy constructor **/ 31 | public Json(Map properties) { 32 | map = unwrap(properties); 33 | } 34 | 35 | /** Construct a JSON Object with single key and value **/ 36 | public Json(String key, Object value) { 37 | set(key, value); 38 | } 39 | 40 | @Override 41 | /** Get the underlying map that stores keys and values **/ 42 | public Map toMap() { 43 | if( map == null ) 44 | map = readFields(); 45 | 46 | return map; 47 | } 48 | 49 | public boolean hasOwnProperty(String key) { 50 | return containsKey(key); 51 | } 52 | 53 | @Override 54 | /** Convert to JSON string representation **/ 55 | public String toString() { 56 | return JsonSerializer.toJsonString(toMap()); 57 | } 58 | 59 | /** Convert to pretty JSON string with indentation **/ 60 | public String toStringPretty() { 61 | return JsonSerializer.toPrettyString(map); 62 | } 63 | 64 | @Override 65 | public boolean equals(Object it) { 66 | return (it instanceof Json) && toMap().equals( ((Json)it).toMap() ); 67 | } 68 | 69 | @Override 70 | public int hashCode() { 71 | return toMap().hashCode(); 72 | } 73 | 74 | @SuppressWarnings("unchecked") 75 | public T get(String key) { 76 | return (T) toMap().get(key); 77 | } 78 | 79 | @SuppressWarnings({ "unchecked", "rawtypes" }) 80 | /** Get a value or a default value **/ 81 | public T get(String key, T defaultValue) { 82 | Object v = toMap().get(key); 83 | if( defaultValue instanceof Json && v instanceof Map ) v = new Json( (Map) v ); 84 | return v==null ? defaultValue : (T) v; 85 | } 86 | 87 | /** Same as {@link #put(String, Object)} but returns itself for chaining **/ 88 | public Json set(String key, Object val) { 89 | put(key, val); 90 | return this; 91 | } 92 | 93 | @Override 94 | public Object put(String key, Object value) { 95 | return toMap().put(key, unwrap(value)); 96 | } 97 | 98 | public Json putArray(String arrayField, List values) { 99 | List vals = values.stream().map(Json::unwrap).collect(toList()); 100 | put(arrayField, vals); 101 | return this; 102 | } 103 | 104 | @SuppressWarnings("unchecked") 105 | /** Get the map out of Json. Store nested Json objects as Maps **/ 106 | static T unwrap(T val) { 107 | if( val instanceof Json ) return (T) ((Json) val).toMap(); 108 | return val; 109 | } 110 | 111 | /** Merge other json into this one recursively. Overwrites values from other if they exist in this. 112 | * @return this 113 | **/ 114 | public Json merge(Json other) { 115 | MapOps.mergeMaps(toMap(), other.toMap()); 116 | return this; 117 | } 118 | 119 | /** 120 | * Get nested JSON object 121 | * @param keys path to nested object 122 | * @return nested JSON object or {@link #EMPTY} JSON object if nothing found 123 | */ 124 | public Json at(String ... keys) { 125 | Map nested = MapOps.getNested(toMap(), keys); 126 | return (nested == MapOps.EMPTY_MAP) ? EMPTY : new Json(nested); 127 | } 128 | 129 | public List getArray(String key) { 130 | return get(key); 131 | } 132 | 133 | public List getObjects(String key) { 134 | List array = getArray(key); 135 | if(array == null) 136 | return null; 137 | return array.stream() 138 | .map(Json.of::bean) 139 | .collect(toList()); 140 | } 141 | 142 | /** Create a (deep) copy of this Json. **/ 143 | public Json copy() { 144 | return new Json( MapOps.deepCopyMap(toMap()) ); 145 | } 146 | 147 | /** Read declared field values using reflection **/ 148 | Map readFields() { 149 | Map fieldVals = new LinkedHashMap<>(); 150 | for(Field f: getClass().getDeclaredFields()) { 151 | if(f.getName().contains("$")) 152 | continue; 153 | Object val = JsonSerializer.getFieldValue(f, this); 154 | if( val != null && !isStatic(f.getModifiers()) ) 155 | fieldVals.put( f.getName() , val); 156 | } 157 | return fieldVals; 158 | } 159 | 160 | } 161 | 162 | -------------------------------------------------------------------------------- /src/main/java/org/andrejs/json/JsonFactory.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | 4 | import java.io.InputStream; 5 | import java.util.Map; 6 | 7 | public class JsonFactory { 8 | 9 | public Json map(Map map) { 10 | return new Json(map); 11 | } 12 | 13 | public Json string(String jsonString) { 14 | return new Json(JsonSerializer.parse(jsonString)); 15 | } 16 | 17 | public Json bean(Object pojoBean) { 18 | return new Json(JsonSerializer.serialize(pojoBean)); 19 | } 20 | 21 | public Json url(String url) { 22 | return new Json(JsonSerializer.readUrl(url)); 23 | } 24 | 25 | public Json file(String filePath) { 26 | return new Json(JsonSerializer.readFile(filePath)); 27 | } 28 | 29 | public Json bytes(byte[] bytes) { 30 | return new Json(JsonSerializer.readBytes(bytes)); 31 | } 32 | 33 | public Json stream(InputStream stream) { 34 | return new Json(JsonSerializer.readStream(stream)); 35 | } 36 | 37 | public Json keyVal(String key, Object val, Object ... keysAndVals) { 38 | Json json = new Json(key, val); 39 | for(int i = 0; i < keysAndVals.length; i++) { 40 | json.set(keysAndVals[i].toString(), keysAndVals[++i]); 41 | } 42 | return json; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/andrejs/json/JsonSerializer.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.io.File; 7 | import java.io.IOError; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.lang.reflect.Field; 11 | import java.net.URL; 12 | import java.util.LinkedHashMap; 13 | import java.util.Map; 14 | 15 | import static com.fasterxml.jackson.core.JsonParser.Feature.*; 16 | 17 | public class JsonSerializer { 18 | 19 | final static ObjectMapper serializer = new ObjectMapper() 20 | .configure(ALLOW_COMMENTS, true).configure(ALLOW_UNQUOTED_CONTROL_CHARS, true) 21 | .configure(ALLOW_SINGLE_QUOTES, true).configure(ALLOW_UNQUOTED_FIELD_NAMES, true); 22 | 23 | static String toJsonString(Map val) { 24 | try { 25 | return serializer.writeValueAsString(val); 26 | } catch (JsonProcessingException e) { 27 | throw new IllegalArgumentException(e); 28 | } 29 | } 30 | 31 | /** Get JSON with indentation **/ 32 | public static String toPrettyString(Map val) { 33 | try { 34 | return serializer.writerWithDefaultPrettyPrinter().writeValueAsString(val); 35 | } catch (JsonProcessingException e) { 36 | throw new IllegalArgumentException(e); 37 | } 38 | } 39 | 40 | @SuppressWarnings("unchecked") 41 | static Map parse(String jsonString) { 42 | try { 43 | if( jsonString.isEmpty() ) return new LinkedHashMap(); 44 | return serializer.readValue(jsonString, Map.class); 45 | } catch (IOException e) { 46 | throw new IllegalStateException(e); 47 | } 48 | } 49 | 50 | static Map readUrl(String url) { 51 | try { 52 | return serializer.readValue(new URL(url), Map.class); 53 | } catch (IOException e) { 54 | throw new IOError(e); 55 | } 56 | } 57 | 58 | static Map readFile(String filePath) { 59 | try { 60 | return serializer.readValue(new File(filePath), Map.class); 61 | } catch (IOException e) { 62 | throw new IOError(e); 63 | } 64 | } 65 | 66 | public static void writeFile(String filePath, Map json) { 67 | try { 68 | serializer.writeValue(new File(filePath), json); 69 | } catch (IOException e) { 70 | throw new IOError(e); 71 | } 72 | } 73 | 74 | static Map readBytes(byte[] json) { 75 | try { 76 | return serializer.readValue(json, Map.class); 77 | } catch (IOException e) { 78 | throw new IOError(e); 79 | } 80 | } 81 | 82 | static Map readStream(InputStream json) { 83 | try { 84 | return serializer.readValue(json, Map.class); 85 | } catch (IOException e) { 86 | throw new IOError(e); 87 | } 88 | } 89 | 90 | @SuppressWarnings("unchecked") 91 | static Map serialize(Object pojoBean) { 92 | try { 93 | if(pojoBean instanceof Map) 94 | return (Map) pojoBean; 95 | return serializer.convertValue(pojoBean, Map.class); 96 | } catch (Exception e) { 97 | throw new IllegalStateException(e); 98 | } 99 | } 100 | 101 | static Object getFieldValue(Field f, Object o) { 102 | try { 103 | f.setAccessible(true); 104 | return f.get(o); 105 | } catch (IllegalAccessException e) { 106 | throw new IllegalStateException(e); 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/org/andrejs/json/MapBindings.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import javax.script.Bindings; 4 | import java.util.Collection; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | /** {@link Bindings} that delegate operations to a {@link Map} **/ 9 | public abstract class MapBindings implements Bindings { 10 | 11 | public abstract Map toMap(); 12 | 13 | @Override 14 | public int size() { 15 | return toMap().size(); 16 | } 17 | 18 | @Override 19 | public boolean isEmpty() { 20 | return toMap().isEmpty(); 21 | } 22 | 23 | @Override 24 | public boolean containsValue(Object value) { 25 | return toMap().containsValue(value); 26 | } 27 | 28 | @Override 29 | public void clear() { 30 | toMap().clear(); 31 | } 32 | 33 | @Override 34 | public Set keySet() { 35 | return toMap().keySet(); 36 | } 37 | 38 | @Override 39 | public Collection values() { 40 | return toMap().values(); 41 | } 42 | 43 | @Override 44 | public Set> entrySet() { 45 | return toMap().entrySet(); 46 | } 47 | 48 | @Override 49 | public Object put(String name, Object value) { 50 | return toMap().put(name, value); 51 | } 52 | 53 | @Override 54 | public void putAll(Map toMerge) { 55 | toMap().putAll(toMerge); 56 | } 57 | 58 | @Override 59 | public boolean containsKey(Object key) { 60 | return toMap().containsKey(key); 61 | } 62 | 63 | @Override 64 | @Deprecated 65 | public Object get(Object key) { 66 | return toMap().get(key); 67 | } 68 | 69 | @Override 70 | public Object remove(Object key) { 71 | return toMap().get(key); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/andrejs/json/MapOps.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import java.util.*; 4 | import java.util.Map.Entry; 5 | 6 | import static java.util.Collections.emptyMap; 7 | 8 | /** Map operations **/ 9 | public class MapOps { 10 | 11 | public static Map EMPTY_MAP = Collections.emptyMap(); 12 | 13 | @SuppressWarnings({ "rawtypes", "unchecked" }) 14 | /** Get nested map or emptyMap() if nothing found **/ 15 | public static Map getNested(Map map, K ... keys) { 16 | Map cur = map; 17 | 18 | for(K key : keys) { 19 | if( cur.get(key) instanceof Map ) 20 | cur = (Map) cur.get(key); 21 | else return emptyMap(); 22 | } 23 | 24 | return cur; 25 | } 26 | 27 | @SuppressWarnings({ "unchecked", "rawtypes" }) 28 | /** Merge two maps recursively **/ 29 | public static void mergeMaps(Map m1, Map m2) { 30 | 31 | for(Entry e: m2.entrySet()) { 32 | Object otherVal = e.getValue(); 33 | if( otherVal instanceof Map ) { 34 | Object myVal = m1.get(e.getKey()); 35 | if( myVal instanceof Map ) 36 | mergeMaps( (Map) myVal, (Map) otherVal ); 37 | else 38 | m1.put(e.getKey(), otherVal); 39 | 40 | } else { 41 | m1.put(e.getKey(), otherVal); 42 | } 43 | } 44 | } 45 | 46 | /** Create a deep copy of map. If a value is a {@link List}, deep copy it as well. **/ 47 | @SuppressWarnings("unchecked") 48 | public static Map deepCopyMap(Map map) { 49 | Map ret = new LinkedHashMap(map.size()); 50 | 51 | for(Entry e: map.entrySet()) 52 | ret.put(e.getKey(), (V) deepCopyCollection(e.getValue())); 53 | 54 | return ret; 55 | } 56 | 57 | @SuppressWarnings("unchecked") 58 | static List deepCopyList(List list) { 59 | List ret = new ArrayList(list.size()); 60 | 61 | for(E e: list) 62 | ret.add( (E) deepCopyCollection(e) ); 63 | 64 | return ret; 65 | } 66 | 67 | @SuppressWarnings({ "unchecked", "rawtypes" }) 68 | static Object deepCopyCollection(Object val) { 69 | if( val instanceof List ) 70 | return deepCopyList( (List) val); 71 | else if(val instanceof Map) 72 | return deepCopyMap( (Map) val ); 73 | else 74 | return val; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/test/java/org/andrejs/json/JsonFactoryTest.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import org.junit.Test; 4 | 5 | import java.io.ByteArrayInputStream; 6 | import java.io.InputStream; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | 10 | import static java.util.Collections.singletonMap; 11 | import static org.junit.Assert.assertEquals; 12 | 13 | public class JsonFactoryTest { 14 | 15 | private JsonFactory it = Json.of; 16 | 17 | @Test 18 | public void map() throws Exception { 19 | assertEquals(new Json("key", "val"), it.map(singletonMap("key", "val"))); 20 | } 21 | 22 | @Test 23 | public void string() throws Exception { 24 | assertEquals(new Json("key", "val"), it.string("{key: \"val\"}")); 25 | } 26 | 27 | @Test 28 | public void bean() throws Exception { 29 | assertEquals(new Json("key", "val"), it.bean(new Bean())); 30 | } 31 | 32 | @Test 33 | public void file() throws Exception { 34 | Path tempFile = Files.createTempFile("json", "test"); 35 | Files.write(tempFile, "{key: \"val\"}".getBytes()); 36 | 37 | assertEquals(new Json("key", "val"), it.file(tempFile.toString())); 38 | } 39 | 40 | @Test 41 | public void url() throws Exception { 42 | Path tempFile = Files.createTempFile("json", "test"); 43 | Files.write(tempFile, "{key: \"val\"}".getBytes()); 44 | 45 | assertEquals(new Json("key", "val"), it.url("file://" + tempFile.toString())); 46 | } 47 | 48 | 49 | @Test 50 | public void bytes() throws Exception { 51 | assertEquals(new Json("key", "val"), it.bytes("{key: \"val\"}".getBytes())); 52 | } 53 | 54 | @Test 55 | public void stream() throws Exception { 56 | InputStream stream = new ByteArrayInputStream("{key: \"val\"}".getBytes()); 57 | assertEquals(new Json("key", "val"), it.stream(stream)); 58 | } 59 | 60 | @Test 61 | public void keyVal() throws Exception { 62 | assertEquals(new Json("key", "val").set("key2", 123), it.keyVal("key", "val", "key2", 123)); 63 | } 64 | 65 | public static class Bean { 66 | public String key = "val"; 67 | } 68 | } -------------------------------------------------------------------------------- /src/test/java/org/andrejs/json/JsonScriptingTest.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import javax.script.Invocable; 7 | import javax.script.ScriptEngine; 8 | import javax.script.ScriptEngineManager; 9 | 10 | import static org.junit.Assert.assertEquals; 11 | import static org.junit.Assert.assertNotNull; 12 | 13 | 14 | public class JsonScriptingTest { 15 | 16 | ScriptEngine eng; 17 | Invocable inv; 18 | 19 | @Before 20 | public void getNashorn() { 21 | eng = new ScriptEngineManager().getEngineByName("Nashorn"); 22 | assertNotNull("Nashorn javascript engine not found", eng); 23 | inv = (Invocable) eng; 24 | } 25 | 26 | @Test 27 | public void usableInScriptEngineAsBindings() throws Exception { 28 | 29 | Json j = new Json("a", 5); 30 | 31 | Double result = (Double) eng.eval("a+1", j); 32 | 33 | assertEquals(6, result.intValue()); 34 | } 35 | 36 | @Test 37 | public void usableAsFunctionArgument() throws Exception { 38 | 39 | Json j = new Json("a", 5); 40 | 41 | eng.eval("function inc(j){ j.b = j.a+1; }"); 42 | 43 | inv.invokeFunction("inc", j); 44 | 45 | assertEquals(6, j.get("b", 0D).intValue()); 46 | } 47 | 48 | @Test 49 | public void modifiableAsFunctionArgument() throws Exception { 50 | 51 | Json addr = new Json("port", 80); 52 | 53 | eng.eval("function nextPort(addr) { addr.port++; }"); 54 | 55 | inv.invokeFunction("nextPort", addr); 56 | 57 | assertEquals(81, addr.get("port", 0.0).intValue()); 58 | } 59 | 60 | @Test 61 | public void canIterateKeysInJs() throws Exception { 62 | 63 | Json j = new Json("a", 5).set("b", 6); 64 | Json j2 = new Json(); 65 | 66 | eng.eval("function it(j, j2){ for(key in j) j2[key] = j[key]; }"); 67 | 68 | inv.invokeFunction("it", j, j2); 69 | 70 | assertEquals(j, j2); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/org/andrejs/json/JsonTest.java: -------------------------------------------------------------------------------- 1 | package org.andrejs.json; 2 | 3 | import org.junit.Test; 4 | 5 | import java.util.Collections; 6 | import java.util.Map; 7 | 8 | import static java.util.Arrays.asList; 9 | import static java.util.Collections.singletonMap; 10 | import static org.junit.Assert.*; 11 | 12 | 13 | public class JsonTest { 14 | 15 | @Test 16 | public void newJsonIsEmpty() throws Exception { 17 | assertTrue( new Json().isEmpty() ); 18 | assertEquals(Json.EMPTY, new Json()); 19 | } 20 | 21 | @Test 22 | public void containsConstructorKeyValue() throws Exception { 23 | Json json = new Json("key", 123); 24 | assertTrue( json.containsKey("key") ); 25 | int val = json.get("key"); 26 | assertEquals(123, val); 27 | } 28 | 29 | @Test 30 | public void containsConstructorMap() throws Exception { 31 | Object val = 123; 32 | Map map = Collections.singletonMap("key", val); 33 | Json json = new Json( map ); 34 | assertTrue( json.containsKey("key") ); 35 | assertEquals(val, json.get("key")); 36 | } 37 | 38 | @Test 39 | @SuppressWarnings("unused") 40 | public void containsAnonymousClassFields() throws Exception { 41 | Json json = new Json() { 42 | int key = 123; 43 | String key2 = "val"; 44 | }; 45 | int val = json.get("key"); 46 | System.out.println(json); 47 | assertEquals(123, val); 48 | assertEquals("val", json.get("key2")); 49 | } 50 | 51 | @Test 52 | public void createdWithHasValues() throws Exception { 53 | assertEquals(new Json("key", 123), new Json("{key: 123}")); 54 | } 55 | 56 | @Test 57 | public void listPropertyProducesArrayInJson() throws Exception { 58 | Json json = new Json("key", asList(1, 2)); 59 | assertEquals("{\"key\":[1,2]}", json.toString()); 60 | } 61 | 62 | @Test 63 | public void toStringGiveJson() throws Exception { 64 | Json json = new Json("key", 123); 65 | assertEquals("{\"key\":123}", json.toString()); 66 | } 67 | 68 | @Test 69 | public void twoJsonsWithSamePropertiesAreEqual() throws Exception { 70 | Json json = new Json("key", 123).set("key2", "val").set("n", new Json("a", 1)); 71 | Json json2 = new Json("key2", "val").set("key", 123).set("n", new Json("a", 1)); 72 | 73 | assertEquals( json, json2 ); 74 | assertEquals( json.hashCode(), json2.hashCode() ); 75 | } 76 | 77 | @Test 78 | public void getReturnsDefaultValueForMissingKey() throws Exception { 79 | assertEquals("val", new Json().get("key", "val") ); 80 | 81 | assertEquals("val", new Json("key", "val").get("key", "val2") ); 82 | } 83 | 84 | @Test 85 | public void atReturnsNestedJson() throws Exception { 86 | Json j = new Json("a", new Json("b", new Json("c", 1))); 87 | 88 | assertEquals(new Json("c", 1), j.at("a", "b")); 89 | assertTrue( j.at("a", "c").isEmpty() ); 90 | assertEquals(Json.EMPTY, j.at("a", "c") ); 91 | 92 | } 93 | 94 | @Test 95 | public void getWithDefaultValueReturnsNestedJson() throws Exception { 96 | Json j = new Json("a", new Json("b", 1)); 97 | 98 | assertEquals(new Json("b", 1), j.get("a", Json.EMPTY)); 99 | assertEquals( singletonMap("b", 1), j.get("a") ); 100 | assertEquals(Json.EMPTY, j.get("missing", Json.EMPTY)); 101 | } 102 | 103 | @Test 104 | public void mergeProducesCombinedJson() throws Exception { 105 | Json j1 = new Json("a", new Json("b", 1)).set("c", 1); 106 | Json j2 = new Json("a", new Json("b", 2)).set("d", 1); 107 | 108 | Json expected = new Json("a", new Json("b", 2)).set("c", 1).set("d", 1); 109 | 110 | assertEquals(expected, j1.merge(j2)); 111 | j2.set("e", 1); 112 | assertEquals(expected, j1); 113 | } 114 | 115 | @Test 116 | public void copyMakesDeepCopy() throws Exception { 117 | Json j1 = new Json("a", new Json("b", 1)); 118 | Json copy = j1.copy(); 119 | 120 | assertEquals(j1, copy); 121 | copy.set("c", 1); 122 | assertNotSame(j1, copy); 123 | } 124 | 125 | @Test 126 | public void getArray() throws Exception { 127 | Json json = new Json("{key: [1, 2]}"); 128 | assertEquals(asList(1, 2), json.getArray("key")); 129 | } 130 | 131 | @Test 132 | public void putArray() throws Exception { 133 | Json json = new Json().putArray("key", asList(1, 2)); 134 | Json expected = new Json("{key: [1, 2]}"); 135 | 136 | assertEquals(expected, json); 137 | } 138 | 139 | @Test 140 | public void getObjects() throws Exception { 141 | Json o1 = new Json("a", 1), o2 = new Json("a", 2); 142 | Json json = new Json("{key: [{a: 1}, {a: 2}]}"); 143 | 144 | assertEquals(asList(o1, o2), json.getObjects("key")); 145 | } 146 | 147 | @Test 148 | public void putObjects() throws Exception { 149 | Json o1 = new Json("a", 1), o2 = new Json("a", 2); 150 | Json expected = new Json("{key: [{a: 1}, {a: 2}]}"); 151 | Json json = new Json().putArray("key", asList(o1, o2)); 152 | 153 | assertEquals(expected, json); 154 | } 155 | } 156 | --------------------------------------------------------------------------------