### Main method for example execution Source: https://github.com/stleary/json-java/blob/master/Examples.md This is the main entry point for the application. It contains commented-out calls to various example methods, allowing selective execution of different functionalities. ```java public static void main(String[] args) { //JSONObjectToArray(); //JSONExampleArray1(); //JSONExampleArray2(); //JSONExampleStringer(); //JSONExampleObject1(); //JSONExampleObject2(); //JSONExampleObject3(); //JSONExamplWriter(); //XMLToExampleConversion(); //XMLFromExampleConversion(); //CookieToExampleConversion(); //CookieFromExampleConversion(); //HTTPToExampleConversion(); //HTTPFromExampleConversion(); //CDLToExampleConversion(); //CDLFromExampleConversion(); //PropertyToExampleConversion(); //PropertyFromExampleConversion(); } ``` -------------------------------- ### Common Imports for JSON-Java Source: https://github.com/stleary/json-java/blob/master/Examples.md Standard imports required for the provided examples. ```java import java.util.HashMap; import java.util.Map; import java.util.Properties; ``` -------------------------------- ### Retrieve Values from JSONObject Source: https://context7.com/stleary/json-java/llms.txt Shows how to retrieve values from a JSONObject using 'get' methods (which throw exceptions on missing keys) and 'opt' methods (which return default values). Includes checking for key existence and iterating over keys. ```java import org.json.JSONObject; import org.json.JSONArray; import java.math.BigDecimal; String json = "{\"name\":\"Alice\",\"age\":28,\"salary\":75000.50,\"active\":true,\"skills\":[\"Java\",\"Python\"],\"address\":{\"city\":\"Boston\"}}"; JSONObject jo = new JSONObject(json); // Using get methods (throws JSONException if key not found) String name = jo.getString("name"); // "Alice" int age = jo.getInt("age"); // 28 double salary = jo.getDouble("salary"); // 75000.5 boolean active = jo.getBoolean("active"); // true JSONArray skills = jo.getJSONArray("skills"); // ["Java","Python"] JSONObject address = jo.getJSONObject("address"); // Using opt methods (returns default value if key not found) String nickname = jo.optString("nickname", "N/A"); // "N/A" (key doesn't exist) int bonus = jo.optInt("bonus", 0); // 0 (key doesn't exist) long id = jo.optLong("id"); // 0L (default when not found) BigDecimal amount = jo.optBigDecimal("salary", BigDecimal.ZERO); // 75000.5 // Check if key exists boolean hasName = jo.has("name"); // true boolean isNull = jo.isNull("phone"); // true (key doesn't exist) // Get all keys for (String key : jo.keySet()) { System.out.println(key + ": " + jo.get(key)); } ``` -------------------------------- ### Maven Deployment Commands Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-make-a-new-JSON-java-release Commands to prepare the repository and execute the deployment to Maven Central. ```bash git checkout master git pull git status # to confirm no local changes mvn clean deploy -Dgpg.passphrase="(your gpg passphrase)" ``` -------------------------------- ### Create Jar File with Jar Source: https://github.com/stleary/json-java/blob/master/README.md Create a JAR file containing the compiled class files of the org.json package. This command should be run from the directory where the .class files were generated. ```shell jar cf json-java.jar org/json/*.class ``` -------------------------------- ### Execute Test Suite with Gradlew Source: https://github.com/stleary/json-java/blob/master/README.md Run the unit tests for the JSON-Java project using Gradle Wrapper. This command performs a clean build and then executes the tests. ```shell gradlew clean build test ``` -------------------------------- ### Build Class Files with Javac Source: https://github.com/stleary/json-java/blob/master/README.md Compile the Java source files for the org.json package from the command line. Ensure you are in the package root directory. ```shell javac org/json/*.java ``` -------------------------------- ### Build and Package JSON-Java Source: https://github.com/stleary/json-java/wiki/FAQ Commands to compile the source code and create a JAR file for distribution on different operating systems. ```bash javac *.java mkdir -p org/json mv *.class org/json jar cf json-java.jar org ``` ```batch javac *.java mkdir org\json move *.class org\json jar cf json-java.jar org ``` -------------------------------- ### Execute Test Suite with Maven Source: https://github.com/stleary/json-java/blob/master/README.md Run the unit tests for the JSON-Java project using Maven. This command executes a clean build and then runs the tests. ```shell mvn clean test ``` -------------------------------- ### Create and Populate JSONObject Source: https://context7.com/stleary/json-java/llms.txt Demonstrates creating an empty JSONObject and adding key-value pairs using method chaining. Also shows creating a JSONObject from a JSON string and a Java Map. ```java import org.json.JSONObject; import org.json.JSONArray; import java.util.HashMap; import java.util.Map; // Create empty JSONObject and add values using method chaining JSONObject jo = new JSONObject() .put("name", "John Doe") .put("age", 30) .put("active", true) .put("balance", 1250.75); System.out.println(jo.toString(2)); // Output: // { // "name": "John Doe", // "age": 30, // "active": true, // "balance": 1250.75 // } // Create from JSON string String jsonString = "{\"city\": \"New York\", \"population\": 8336817}"; JSONObject cityObj = new JSONObject(jsonString); System.out.println(cityObj.getString("city")); // Output: New York // Create from Map Map map = new HashMap<>(); map.put("product", "Laptop"); map.put("price", 999.99); map.put("inStock", true); JSONObject productObj = new JSONObject(map); System.out.println(productObj.toString()); // Output: {"product":"Laptop","price":999.99,"inStock":true} ``` -------------------------------- ### Convert XML to JSON with Configuration Source: https://github.com/stleary/json-java/wiki/Home Demonstrates the difference in output when using default settings versus custom configuration to preserve string types. ```java JSONObject jsonObject = XML.toJSONObject("John Doe"); System.out.println(jsonObject.toString()); ``` ```java XMLParserConfiguration config = new XMLParserConfiguration(true); JSONObject jsonObject = XML.toJSONObject("John Doe", config); System.out.println(jsonObject.toString()); ``` -------------------------------- ### Execute Ant Build Source: https://github.com/stleary/json-java/wiki/Tech:-Building-a-Jar-file-with-Apache-Ant After saving the build.xml file, run this command in the terminal from the project's root directory to create the JSON-java.jar file. ```bash $ ant ``` -------------------------------- ### Configure GPG Keys for Maven Deployment Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-make-a-new-JSON-java-release Commands for generating and exporting GPG keys to facilitate secure publishing to Maven Central. ```bash # create a new key, using name, comment, email, and passphrase gpg --gen-key # look for the 'sec' line gpg --list-secret-keys --keyid-format long # may not need this git config user.signingkey (your secret key) # get your public key gpg --armor --export (your secret key pub string) # In GitHub, click your profile pic, select settings > ssh & gpg keys, add the entire public key including framing # Get your public key hash (I think) gpg --list-keys # may not need this - these files seem not to found here anymore - make sure your permissions are good chmod 400 /(directory)/.gnupg/gpg.conf chmod 600 /(directory)/.gnupg # recently keys.gnupg.net seems to have been deprecated, specify a different one ``` -------------------------------- ### XMLParserConfiguration Fluent API Usage Source: https://github.com/stleary/json-java/wiki/Home Shows how to chain configuration methods using the fluent setter pattern. ```java new XMLParserConfiguration().withKeepStrings(true).withcDataTagName("MyCDATA") ``` -------------------------------- ### GPG Key Server Commands Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-make-a-new-JSON-java-release Commands to send GPG keys to a keyserver. ```bash $ gpg --keyserver keys.gnupg.net --send-keys (output from list-keys) $ gpg --keyserver keyserver.ubuntu.com --send-keys (pub key string from list-keys) gpg: sending key (key) to hkp://keyserver.ubuntu.com ``` -------------------------------- ### Create JSON with JSONObject Source: https://github.com/stleary/json-java/blob/master/Examples.md Demonstrates creating a JSONObject from a string, manual key-value insertion, and conversion from a Java Map. ```java private static void JSONExampleObject1() { //We can create a JSONObject from a String with the class builder String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}"; JSONObject example = new JSONObject(string); System.out.println("Final JSONObject: " + example); } ``` ```java private static void JSONExampleObject2() { //We can also create a JSONObject directly without messing around with any of the other functions. JSONObject example = new JSONObject(); //Now we add the keys and values in a similar way as the Stringer method example.put("key", "value"); //As you can see, the first entry is the key and the second would be its associeted value. example.put("key2", 5); example.put("key3", -23.45e67); example.put("trueValue", true); //We can't add null values thougth //example.put("nullValue", null); //This is not possible System.out.println("Final JSONOBject: " + example); } ``` ```java private static void JSONExampleObject3() { //We can also create a JSONObject with a Java Map //YoU will need a Map whose keys are Strings. The values can be whatever you want Map map = new HashMap(); map.put("key1", 1.0); map.put("key2", -23.45e67); //We create the JSONObject with the map with its class builder JSONObject example = new JSONObject(map); System.out.println("Final JSONOBject: " + example); } ``` -------------------------------- ### Update Project Configuration Files Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-make-a-new-JSON-java-release Configuration snippets for updating versioning in build files during the release process. ```xml 20201115 ``` ```gradle (new tag)-SNAPSHOT ``` -------------------------------- ### Compile JSON-Java Source Source: https://github.com/stleary/json-java/wiki/FAQ Basic command to compile all Java source files in the project directory. ```bash javac *.java ``` -------------------------------- ### Verify JAR Contents Source: https://github.com/stleary/json-java/wiki/Tech:-Building-a-Jar-file-with-Apache-Ant This command lists the contents of the generated JSON-java.jar file, showing the compiled Java classes and package structure. ```bash $ jar tf JSON-java.jar ``` -------------------------------- ### Execute Java Test Program (Windows) Source: https://github.com/stleary/json-java/blob/master/README.md Run the compiled Java test program on a Windows system. The classpath must include the current directory and the json-java.jar file. ```shell java -cp .;json-java.jar Test ``` -------------------------------- ### Maven Settings Configuration Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-make-a-new-JSON-java-release Configuration for ~/.m2/settings.xml to authenticate with Sonatype OSSRH using a user token. ```xml ossrh token-username token-password ``` -------------------------------- ### Execute Test Suite in Strict Mode with Gradlew Source: https://github.com/stleary/json-java/blob/master/README.md Run the unit tests in strict mode using Gradle Wrapper. This provides more rigorous testing conditions. ```shell gradlew testWithStrictMode ``` -------------------------------- ### Create and Manipulate JSONArray Source: https://context7.com/stleary/json-java/llms.txt Demonstrates creating JSON arrays from strings, collections, and Java arrays. Includes methods for adding, retrieving, and iterating over elements. Use opt methods for safe retrieval of elements. ```java import org.json.JSONArray; import org.json.JSONObject; import java.util.Arrays; import java.util.List; // Create from JSON string JSONArray colors = new JSONArray("[\"red\", \"green\", \"blue\"]"); System.out.println(colors.getString(0)); // Output: red // Create empty array and add elements JSONArray numbers = new JSONArray(); numbers.put(10) .put(20) .put(30) .put(40); // Create from Java collection List fruits = Arrays.asList("apple", "banana", "orange"); JSONArray fruitArray = new JSONArray(fruits); // Create array of objects JSONArray users = new JSONArray(); users.put(new JSONObject().put("id", 1).put("name", "Alice")); users.put(new JSONObject().put("id", 2).put("name", "Bob")); // Retrieve elements with type checking for (int i = 0; i < users.length(); i++) { JSONObject user = users.getJSONObject(i); System.out.println("User: " + user.getString("name")); } // Use opt methods for safe retrieval String fourth = colors.optString(3, "default"); // "default" (index out of bounds) int value = numbers.optInt(1); // 20 // Convert to Java List List list = numbers.toList(); // Join array elements String joined = colors.join(", "); // "red, green, blue" ``` -------------------------------- ### Execute Java Test Program (Unix Systems) Source: https://github.com/stleary/json-java/blob/master/README.md Run the compiled Java test program on Unix-based systems. The classpath must include the current directory and the json-java.jar file. ```shell java -cp .:json-java.jar Test ``` -------------------------------- ### Build JSON-java JAR with Ant Source: https://github.com/stleary/json-java/wiki/Tech:-Building-a-Jar-file-with-Apache-Ant Save this XML content as build.xml in the project's root directory. This script compiles the Java source files and packages them into a JAR file named JSON-java.jar. ```xml ``` -------------------------------- ### Compile Java Program Using Jar (Windows) Source: https://github.com/stleary/json-java/blob/master/README.md Compile a Java program that utilizes the json-java.jar library on a Windows system. The classpath must include the current directory and the JAR file. ```shell javac -cp .;json-java.jar Test.java ``` -------------------------------- ### Update and Publish JavaDocs Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-update-the-JavaDocs Execute these commands to update the JavaDocs and link to Oracle v7 docs. Assumes the project repo is in the JSON-Java directory. This process involves checking out branches, merging, generating docs, staging, committing, and pushing changes. ```bash cd git checkout master git pull git checkout gh-pages git merge master cd JSON-Java\src\main\java javadoc -d \JSON-Java -link https://docs.oracle.com/javase/7/docs/api/ org.json git add git commit git push ``` -------------------------------- ### Compile Java Program Using Jar (Unix Systems) Source: https://github.com/stleary/json-java/blob/master/README.md Compile a Java program that utilizes the json-java.jar library on Unix-based systems. The classpath must include the current directory and the JAR file. ```shell javac -cp .:json-java.jar Test.java ``` -------------------------------- ### Navigate JSON Documents with JSONPointer Source: https://context7.com/stleary/json-java/llms.txt Use JSONPointer to navigate JSON documents using RFC 6901 path strings. Supports querying values and safe access with optQuery. Pointers can be built programmatically. ```java import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONPointer; String json = "{\"store\": {\"name\": \"Tech Shop\",\"products\": [{\"id\": 1, \"name\": \"Laptop\", \"price\": 999.99},{\"id\": 2, \"name\": \"Mouse\", \"price\": 29.99},{\"id\": 3, \"name\": \"Keyboard\", \"price\": 79.99}],\"location\": {\"city\": \"Seattle\",\"zip\": \"98101\"}}}"; JSONObject root = new JSONObject(json); // Query using string pointer Object storeName = root.query("/store/name"); System.out.println("Store: " + storeName); // Output: Tech Shop // Access array elements by index Object firstProduct = root.query("/store/products/0/name"); System.out.println("First product: " + firstProduct); // Output: Laptop // Use optQuery for safe access (returns null if not found) Object missing = root.optQuery("/store/nonexistent"); System.out.println("Missing: " + missing); // Output: null // Build pointer programmatically JSONPointer pointer = JSONPointer.builder() .append("store") .append("products") .append(1) .append("price") .build(); Object price = pointer.queryFrom(root); System.out.println("Second product price: " + price); // Output: 29.99 // Get URI fragment representation String fragment = pointer.toURIFragment(); System.out.println("URI fragment: " + fragment); // Output: #/store/products/1/price ``` -------------------------------- ### JSONArray putAll with mixed wrapping Source: https://github.com/stleary/json-java/blob/master/docs/NOTES.md Demonstrates how using putAll on a JSONArray with different types of inputs can lead to inconsistent object representation. It's recommended to ensure consistent wrapping for all elements. ```Java SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) }; JSONArray jArr = new JSONArray(myArr); jArr.putAll(new SomeBean[]{ new SomeBean(3), new SomeBean(4) }); ``` -------------------------------- ### Execute Test Suite in Strict Mode with Maven Source: https://github.com/stleary/json-java/blob/master/README.md Run the unit tests in strict mode using Maven. This requires activating the 'test-strict-mode' profile. ```shell mvn test -P test-strict-mode ``` -------------------------------- ### Consistent JSONArray putAll - Option 1 Source: https://github.com/stleary/json-java/blob/master/docs/NOTES.md Illustrates the first recommended approach for consistent JSONArray construction using putAll, where elements are not automatically wrapped by JSONObject.wrap. ```Java SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) }; JSONArray jArr = new JSONArray(); jArr.putAll(myArr); jArr.putAll(new SomeBean[]{ new SomeBean(3), new SomeBean(4) }); ``` -------------------------------- ### Create XMLParserConfiguration to Keep Strings in Java Source: https://github.com/stleary/json-java/wiki/Home Instantiate `XMLParserConfiguration` and use the `withKeepStrings(true)` method to ensure that numerical strings in the XML are preserved as strings in the resulting JSON. This is useful for maintaining data integrity. ```java XMLParserConfiguration config = new XMLParserConfiguration().withKeepStrings(true); ``` -------------------------------- ### Static Utility Methods for JSON Formatting Source: https://context7.com/stleary/json-java/llms.txt Utilize static methods like `quote` for properly escaping strings within JSON and `numberToString` for converting numbers to their string representation. ```java // Static utility methods String quoted = JSONObject.quote("Hello \"World\""); System.out.println(quoted); // "Hello \"World\"" String numStr = JSONObject.numberToString(123.456); System.out.println(numStr); // 123.456 ``` -------------------------------- ### Consistent JSONArray putAll - Option 2 Source: https://github.com/stleary/json-java/blob/master/docs/NOTES.md Presents the second recommended method for consistent JSONArray construction using putAll, ensuring all elements are wrapped by JSONObject.wrap by converting array inputs to JSONArrays first. ```Java SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) }; JSONArray jArr = new JSONArray(myArr); jArr.putAll(new JSONArray(new SomeBean[]{ new SomeBean(3), new SomeBean(4) })); ``` -------------------------------- ### XMLParserConfiguration Source: https://github.com/stleary/json-java/wiki/Home Configuration settings for the XML parser to handle data types, CDATA, and nesting depth. ```APIDOC ## Configuration Properties ### Description Settings available for customizing the XML parsing process via fluent setter methods. ### Parameters - **withKeepStrings(boolean)** - If true, values are not converted to numbers, booleans, or null. - **withcDataTagName(String)** - Sets the tag name used for CDATA sections. - **withConvertNilAttributeToNull(boolean)** - If true, converts nil attributes to JSONNull. - **withXsiTypeMap(Map>)** - Maps xsi:type attributes to specific target types. - **withForceList(Set)** - Forces specified tags to be treated as JSONArray entries. - **withMaxNestingDepth(int)** - Sets the maximum allowed nesting depth (default 512). ``` -------------------------------- ### Java Test Program for JSONObject Source: https://github.com/stleary/json-java/blob/master/README.md A simple Java program that demonstrates creating a JSONObject from a string and printing it to the console. This requires the org.json library to be available. ```java import org.json.JSONObject; public class Test { public static void main(String args[]){ JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }"); System.out.println(jo); } } ``` -------------------------------- ### Create JSON from JSONArray Source: https://github.com/stleary/json-java/blob/master/Examples.md Demonstrates creating a JSONObject from a JSON array string or by manually adding elements to a JSONArray. ```java private static void JSONExampleArray1() { //We create a JSONObject from a String containing an array using JSONArray //Firstly, we declare an Array in a String String arrayStr = "["+"true,"+"false,"+ "\"true\","+ "\"false\","+"\"hello\","+"23.45e-4,"+ "\"23.45\","+"42,"+"\"43\","+"["+"\"world\""+"],"+ "{"+ "\"key1\":\"value1\","+ "\"key2\":\"value2\","+ "\"key3\":\"value3\","+ "\"key4\":\"value4\""+ "},"+ "0,"+"\"-1\""+ "]"; //Then, we initializate the JSONArray thanks to its constructor JSONArray array = new JSONArray(arrayStr); System.out.println("Values array: "+ array); //We convert that array into a JSONObject, but first, we need the labels, so we need another JSONArray with the labels. //Here we will use an auxiliary function to get one for the example. JSONArray list = listNumberArray(array.length()); System.out.println("Label Array: "+ list.toString()); //Now, we construct the JSONObject using both the value array and the label array. JSONObject object = array.toJSONObject(list); System.out.println("Final JSONOBject: " + object); } //This method creates an JSONArray of labels in which those are generated by their positions private static JSONArray listNumberArray(int max){ JSONArray res = new JSONArray(); for (int i=0; i items; public Map prices; } String orderJson = "{\"orderId\":123,\"items\":[\"apple\",\"banana\"],\"prices\":{\"apple\":1.5,\"banana\":0.75}}"; Order order = JSONObject.fromJson(orderJson, Order.class); ``` -------------------------------- ### Write JSON Object with JSONWriter Source: https://github.com/stleary/json-java/blob/master/Examples.md Use JSONWriter to programmatically build a JSON object by appending keys and values. Requires an Appendable object like StringBuilder. ```java StringBuilder write = new StringBuilder(); JSONWriter jsonWriter = new JSONWriter(write); jsonWriter.object(); jsonWriter.key("trueValue").value(true); jsonWriter.key("falseValue").value(false); jsonWriter.key("nullValue").value(null); jsonWriter.key("stringValue").value("hello world!"); jsonWriter.key("complexStringValue").value("h\be\tllo w\u1234orld!"); jsonWriter.key("intValue").value(42); jsonWriter.key("doubleValue").value(-23.45e67); jsonWriter.endObject(); System.out.println("JSON: " + write.toString()); ``` -------------------------------- ### Create JSONTokener from String Source: https://github.com/stleary/json-java/blob/master/Examples.md Initialize a JSONTokener with a string, which can then be used to create JSONObjects or JSONArrays. Note that the string does not need to be valid JSON. ```java String string = "this is not a valid JSON string"; JSONTokener token = new JSONTokener(string); JSONObject object = new JSONObject(token); JSONArray array = new JSONArray(token); ``` -------------------------------- ### Write JSON to Output Streams Source: https://context7.com/stleary/json-java/llms.txt Writes JSON data directly to Writer objects for memory-efficient output. Supports pretty-printing via indentation parameters. ```java import org.json.JSONObject; import org.json.JSONArray; import java.io.StringWriter; import java.io.FileWriter; JSONObject data = new JSONObject() .put("id", 1) .put("name", "Test") .put("values", new JSONArray().put(1).put(2).put(3)); // Write compact JSON to StringWriter StringWriter sw = new StringWriter(); data.write(sw); System.out.println(sw.toString()); // {"id":1,"name":"Test","values":[1,2,3]} // Write pretty-printed JSON with indentation StringWriter pretty = new StringWriter(); data.write(pretty, 2, 0); // indentFactor=2, indent=0 System.out.println(pretty.toString()); // Output: // { // "id": 1, // "name": "Test", // "values": [ // 1, // 2, // 3 // ] // } // Write directly to file try (FileWriter fw = new FileWriter("output.json")) { data.write(fw, 2, 0); } // JSONArray also supports write methods JSONArray array = new JSONArray().put("a").put("b").put("c"); StringWriter arraySw = new StringWriter(); array.write(arraySw, 2, 0); ``` -------------------------------- ### Serialize Java Beans to JSON Source: https://context7.com/stleary/json-java/llms.txt Uses @JSONPropertyName and @JSONPropertyIgnore annotations to control field mapping and exclusion during serialization. ```java import org.json.JSONObject; import org.json.JSONPropertyName; import org.json.JSONPropertyIgnore; // Simple Java bean public class Person { private String firstName; private String lastName; private int age; private String password; public Person(String firstName, String lastName, int age, String password) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.password = password; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } // Custom JSON property name @JSONPropertyName("full_name") public String getFullName() { return firstName + " " + lastName; } // Exclude from JSON output @JSONPropertyIgnore public String getPassword() { return password; } } // Usage Person person = new Person("John", "Doe", 30, "secret123"); JSONObject json = new JSONObject(person); System.out.println(json.toString(2)); // Output: // { // "firstName": "John", // "lastName": "Doe", // "age": 30, // "full_name": "John Doe" // } // Note: password is excluded, fullName uses custom key // Serialize only specific fields JSONObject partial = new JSONObject(person, new String[]{"firstName", "age"}); System.out.println(partial.toString()); // {"firstName":"John","age":30} ``` -------------------------------- ### Convert JSONObject to Properties Source: https://github.com/stleary/json-java/blob/master/Examples.md Use the Property.toProperties() method to convert a JSONObject into a Java Properties object. The keys and values of the JSONObject are directly mapped to the Properties object. ```java String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}"; JSONObject example = new JSONObject(string); //We obtain a String with Properties format with toString() Properties output = Property.toProperties(example); System.out.println("Final Properties: " + output); return output; ``` -------------------------------- ### Implement JSONString for Custom Serialization Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-solve-specific-problems-in-your-JSON-Java-code Implement the `JSONString` interface in your POJO to define a custom `toJSONString()` method. This method controls how the object is serialized into a JSON string, allowing selective field inclusion and custom formatting. ```java public class MyPoJo implements org.json.JSONString { private String someField; // pretend getters and setters private int someOtherField; // pretend getters and setters private ZonedDateTime aDate; // pretend getters and setters @Override public String toJSONString() { // notice the lack of "someOtherField" return "{" + "\"someField\": ``` ```java + JSONObject.quote(this.someField) + ",\"aDate\": ``` ```java + JSONObject.quote(formatMyDate()) + "}"; } private String formatMyDate() { /* some implementation that formats your date a specific way */ } } ``` -------------------------------- ### Convert Properties to JSONObject Source: https://github.com/stleary/json-java/blob/master/Examples.md Use the Property.toJSONObject() method to convert a Java Properties object into a JSONObject. This is useful for integrating Java's configuration properties with JSON data structures. ```java //We start with a Properties object Properties input = PropertyToExampleConversion(); //We obtain a JSONObject with toJSONOBject() JSONObject output = Property.toJSONObject(input); System.out.println("Final JSONObject: " + output); ``` -------------------------------- ### JSONArray Iteration Source: https://github.com/stleary/json-java/wiki/FAQ Implementation of the Iterable interface for JSONArray. ```APIDOC ## JSONArray Iteration ### Description JSONArray now implements Iterable, allowing for standard Java iteration patterns. ### Methods - JSONArray.iterator() ``` -------------------------------- ### Serialize Collection with Custom POJOs Source: https://github.com/stleary/json-java/wiki/Tech:-How-to-solve-specific-problems-in-your-JSON-Java-code When a collection of objects implementing `JSONString` is passed to the `JSONArray` constructor, the `toJSONString()` method of each object is automatically invoked during serialization. This ensures your custom formatting is applied. ```java // then somewhere else in code: Collection cMP = getACollectionFromSomewhere(); JSONArray ja = new JSONArray(cMP); // at this point, the items in the JSONArray are still MyPoJo, not a string or JSONObject // if you want you can still work with the POJO through the JSONArray // the following will cause the `MyPoJo.toJSONString` to be called for each MyPoJo in the list // the output will be as you expect with the POJO formatted as we customized. return ja.ToString(); ``` -------------------------------- ### Convert JSON to HTTP Cookie String with json-java Source: https://context7.com/stleary/json-java/llms.txt Use the Cookie.toString method to convert a JSONObject into an HTTP cookie string. Ensure the JSONObject contains the necessary keys like 'name', 'value', and optional attributes. Boolean values for 'secure' and 'httponly' are correctly formatted. ```java import org.json.Cookie; import org.json.JSONObject; // Create cookie string from JSONObject JSONObject newCookie = new JSONObject() .put("name", "user_id") .put("value", "12345") .put("path", "/app") .put("max-age", "86400") .put("secure", true); String cookieOutput = Cookie.toString(newCookie); System.out.println(cookieOutput); // Output: user_id=12345;path=/app;max-age=86400;secure ``` -------------------------------- ### Check Similarity Between JSONObjects Source: https://context7.com/stleary/json-java/llms.txt The `similar` method performs a deep comparison between two `JSONObject` instances, treating numeric values that are mathematically equal as identical. ```java // Check similarity (deep equals with number comparison) JSONObject obj1 = new JSONObject("{\"val\": 1.0}"); JSONObject obj2 = new JSONObject("{\"val\": 1}"); boolean similar = obj1.similar(obj2); // true ``` -------------------------------- ### XML.toJSONObject Source: https://github.com/stleary/json-java/wiki/Home Converts an XML string into a JSONObject, optionally using a configuration object to control type conversion. ```APIDOC ## POST /XML/toJSONObject ### Description Converts an XML string into a JSONObject. The conversion behavior can be customized using an optional XMLParserConfiguration object. ### Method POST ### Endpoint /XML/toJSONObject ### Parameters #### Request Body - **xmlString** (string) - Required - The XML content to be converted. - **config** (XMLParserConfiguration) - Optional - Configuration object to define parsing behavior (e.g., keepStrings, maxNestingDepth). ### Request Example { "xmlString": "John Doe", "config": { "keepStrings": true } } ### Response #### Success Response (200) - **jsonObject** (object) - The resulting JSON representation of the XML input. #### Response Example { "person": { "age": "30", "content": "John Doe" } } ``` -------------------------------- ### Convert JSONObject to HTTP String Source: https://github.com/stleary/json-java/blob/master/Examples.md Convert a JSONObject into an HTTP formatted string using the HTTP.toString() method. The JSONObject must contain minimum headers for an HTTP request or header. ```java String string = "{\"Method\":\"POST\",\"Request-URI\":'/',\"HTTP-Version\":'HTTP/1.1',\"Value1\":true,\"Value2\":2,\"Value3\":-2.345E68}"; JSONObject example = new JSONObject(string); String output = HTTP.toString(example); System.out.println("Final HTTP: " + output); ``` -------------------------------- ### Numeric Type Accessors Source: https://github.com/stleary/json-java/wiki/FAQ Methods for retrieving BigDecimal and BigInteger values from JSONArray and JSONObject. ```APIDOC ## Numeric Accessors ### Description Provides methods to extract high-precision numeric types from JSON objects and arrays. ### Methods - JSONArray.getBigDecimal(int index) - JSONArray.getBigInteger(int index) - JSONArray.optBigInteger(int index, BigInteger defaultValue) - JSONArray.optBigDecimal(int index, BigDecimal defaultValue) - JSONObject.getBigInteger(String key) - JSONObject.getBigDecimal(String key) - JSONObject.optBigInteger(String key, BigInteger defaultValue) - JSONObject.optBigDecimal(String key, BigDecimal defaultValue) ``` -------------------------------- ### Convert JSONObject to Cookie String Source: https://github.com/stleary/json-java/blob/master/Examples.md Convert a JSONObject into a Cookie formatted string using the Cookie.toString() method. The JSONObject must contain 'name' and 'value' entries. Note that Cookie format does not support booleans. ```java String string = "{\"name\":\"Cookie-Name\",\"value\":\"name\",\"1\":5,\"2\":-2.345E68,\"3\":'true'}"; JSONObject example = new JSONObject(string); String output = Cookie.toString(example); System.out.println("Final Cookie: " + output); ``` -------------------------------- ### Convert JSONObject to JSONArray Source: https://github.com/stleary/json-java/blob/master/Examples.md Convert a JSONObject to a JSONArray by providing a JSONArray of key strings. The order of keys in the keyStrings array determines the order in the resulting JSONArray. ```java String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}"; JSONObject example = new JSONObject(string); JSONArray keyStrings = listNumberArray(example.length()); JSONArray array = example.toJSONArray(keyStrings); System.out.println("Final JSONArray: " + array); ``` -------------------------------- ### Convert JSONObject to Map Source: https://context7.com/stleary/json-java/llms.txt The `toMap` method converts a `JSONObject` into a `java.util.Map`, providing a convenient way to work with JSON data using standard Java Map interfaces. ```java // Convert between JSON and Map JSONObject mapObj = new JSONObject().put("a", 1).put("b", 2); java.util.Map map = mapObj.toMap(); ``` -------------------------------- ### Convert HTTP String to JSONObject Source: https://github.com/stleary/json-java/blob/master/Examples.md Parse an HTTP formatted string into a JSONObject using the HTTP.toJSONObject() method. This enables the conversion of HTTP headers and request information into a structured JSON format. ```java String string = "Final HTTP: POST '/' HTTP/1.1 Value3: -2.345E+68 Value1: true Value2: 2"; JSONObject output = HTTP.toJSONObject(string); System.out.println("Final JSONObject: " + output); ``` -------------------------------- ### Convert Cookie String to JSONObject Source: https://github.com/stleary/json-java/blob/master/Examples.md Parse a Cookie formatted string into a JSONObject using the Cookie.toJSONObject() method. This facilitates the conversion of cookie data into a structured JSON format. ```java String string = "Cookie-Name=name;1=5;2=-2.345E%2b68;3=true"; JSONObject output = Cookie.toJSONObject(string); System.out.println("Final JSONObject: " + output); ``` -------------------------------- ### Convert JSONObject to XML String Source: https://github.com/stleary/json-java/blob/master/Examples.md Convert a JSONObject into an XML formatted string using the XML.toString() method. This is useful for interoperability with systems that use XML. ```java String string = "{\"0\":\"value\",\"1\":5,\"2\":-2.345E68,\"3\":true}"; JSONObject example = new JSONObject(string); String output = XML.toString(example); System.out.println("Final XML: " + output); ```