This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
## JSON
This module contains articles about JSON.
### Relevant Articles:
- [Introduction to JSON Schema in Java](https://www.baeldung.com/introduction-to-json-schema-in-java)
- [A Guide to FastJson](https://www.baeldung.com/fastjson)
- [Introduction to JSONForms](https://www.baeldung.com/introduction-to-jsonforms)
- [Introduction to JsonPath](https://www.baeldung.com/guide-to-jayway-jsonpath)
- [Introduction to JSON-Java (org.json)](https://www.baeldung.com/java-org-json)
- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer)
- [Introduction to the JSON Binding API (JSR 367) in Java](https://www.baeldung.com/java-json-binding-api)
- [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key)
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping)
+96
View File
@@ -0,0 +1,96 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>json</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>json</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
<version>${everit.json.schema.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>${jsonb-api.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://search.maven.org/search?q=g:org.glassfish%20AND%20a:javax.json&core=gav -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>${javax.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>${yasson.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<everit.json.schema.version>1.4.1</everit.json.schema.version>
<fastjson.version>1.2.21</fastjson.version>
<jsonb-api.version>1.0</jsonb-api.version>
<commons-collections4.version>4.1</commons-collections4.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20171018</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<assertj-core.version>3.11.1</assertj-core.version>
</properties>
</project>
@@ -0,0 +1,26 @@
package com.baeldung.adapter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.bind.adapter.JsonbAdapter;
import com.baeldung.jsonb.Person;
public class PersonAdapter implements JsonbAdapter<Person, JsonObject> {
@Override
public JsonObject adaptToJson(Person p) throws Exception {
return Json.createObjectBuilder()
.add("id", p.getId())
.add("name", p.getName())
.build();
}
@Override
public Person adaptFromJson(JsonObject adapted) throws Exception {
Person person = new Person();
person.setId(adapted.getInt("id"));
person.setName(adapted.getString("name"));
return person;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.escape;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import org.json.JSONObject;
class JsonEscape {
String escapeJson(String input) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", input);
return jsonObject.toString();
}
String escapeGson(String input) {
JsonObject gsonObject = new JsonObject();
gsonObject.addProperty("message", input);
return gsonObject.toString();
}
String escapeJackson(String input) throws JsonProcessingException {
return new ObjectMapper().writeValueAsString(new Payload(input));
}
static class Payload {
String message;
Payload(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
@@ -0,0 +1,127 @@
package com.baeldung.jsonb;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbNumberFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbTransient;
public class Person {
private int id;
@JsonbProperty("person-name")
private String name;
@JsonbProperty(nillable = true)
private String email;
@JsonbTransient
private int age;
@JsonbDateFormat("dd-MM-yyyy")
private LocalDate registeredDate;
private BigDecimal salary;
public Person() {
this(0, "", "", 0, LocalDate.now(), new BigDecimal(0));
}
public Person(int id, String name, String email, int age, LocalDate registeredDate, BigDecimal salary) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
this.registeredDate = registeredDate;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonbNumberFormat(locale = "en_US", value = "#0.0")
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public LocalDate getRegisteredDate() {
return registeredDate;
}
public void setRegisteredDate(LocalDate registeredDate) {
this.registeredDate = registeredDate;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append(", age=");
builder.append(age);
builder.append(", registeredDate=");
builder.append(registeredDate);
builder.append(", salary=");
builder.append(salary);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
}
@@ -0,0 +1,59 @@
package com.baeldung.jsonjava;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;
public class CDLDemo {
public static void main(String[] args) {
System.out.println("8.1. Producing JSONArray Directly from Comma Delimited Text: ");
jsonArrayFromCDT();
System.out.println("\n8.2. Producing Comma Delimited Text from JSONArray: ");
cDTfromJSONArray();
System.out.println("\n8.3.1. Producing JSONArray of JSONObjects Using Comma Delimited Text: ");
jaOfJOFromCDT2();
System.out.println("\n8.3.2. Producing JSONArray of JSONObjects Using Comma Delimited Text: ");
jaOfJOFromCDT2();
}
public static void jsonArrayFromCDT() {
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
System.out.println(ja);
}
public static void cDTfromJSONArray() {
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);
System.out.println(cdt);
}
public static void jaOfJOFromCDT() {
String string =
"name, city, age \n" +
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(string);
System.out.println(result.toString());
}
public static void jaOfJOFromCDT2() {
JSONArray ja = new JSONArray();
ja.put("name");
ja.put("city");
ja.put("age");
String string =
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(ja, string);
System.out.println(result.toString());
}
}
@@ -0,0 +1,30 @@
package com.baeldung.jsonjava;
import org.json.Cookie;
import org.json.JSONObject;
public class CookieDemo {
public static void main(String[] args) {
System.out.println("9.1. Converting a Cookie String into a JSONObject");
cookieStringToJSONObject();
System.out.println("\n9.2. Converting a JSONObject into Cookie String");
jSONObjectToCookieString();
}
public static void cookieStringToJSONObject() {
String cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
JSONObject cookieJO = Cookie.toJSONObject(cookie);
System.out.println(cookieJO);
}
public static void jSONObjectToCookieString() {
JSONObject cookieJO = new JSONObject();
cookieJO.put("name", "username");
cookieJO.put("value", "John Doe");
cookieJO.put("expires", "Thu, 18 Dec 2013 12:00:00 UTC");
cookieJO.put("path", "/");
String cookie = Cookie.toString(cookieJO);
System.out.println(cookie);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.jsonjava;
public class DemoBean {
private int id;
private String name;
private boolean active;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.jsonjava;
import org.json.HTTP;
import org.json.JSONObject;
public class HTTPDemo {
public static void main(String[] args) {
System.out.println("10.1. Converting JSONObject to HTTP Header: ");
jSONObjectToHTTPHeader();
System.out.println("\n10.2. Converting HTTP Header String Back to JSONObject: ");
hTTPHeaderToJSONObject();
}
public static void jSONObjectToHTTPHeader() {
JSONObject jo = new JSONObject();
jo.put("Method", "POST");
jo.put("Request-URI", "http://www.example.com/");
jo.put("HTTP-Version", "HTTP/1.1");
System.out.println(HTTP.toString(jo));
}
public static void hTTPHeaderToJSONObject() {
JSONObject obj = HTTP.toJSONObject("POST \"http://www.example.com/\" HTTP/1.1");
System.out.println(obj);
}
}
@@ -0,0 +1,52 @@
package com.baeldung.jsonjava;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONArrayDemo {
public static void main(String[] args) {
System.out.println("6.1. Creating JSON Array: ");
creatingJSONArray();
System.out.println("\n6.2. Creating JSON Array from JSON string: ");
jsonArrayFromJSONString();
System.out.println("\n6.3. Creating JSON Array from Collection Object: ");
jsonArrayFromCollectionObj();
}
public static void creatingJSONArray() {
JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");
// We can also put a JSONObject in JSONArray
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
ja.put(jo);
System.out.println(ja.toString());
}
public static void jsonArrayFromJSONString() {
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
System.out.println(ja);
}
public static void jsonArrayFromCollectionObj() {
List<String> list = new ArrayList<>();
list.add("California");
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");
JSONArray ja = new JSONArray(list);
System.out.println(ja);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.jsonjava;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONArrayGetValueByKey {
public List<String> getValuesByKeyInJSONArray(String jsonArrayStr, String key) {
List<String> values = new ArrayList<>();
JSONArray jsonArray = new JSONArray(jsonArrayStr);
for (int idx = 0; idx < jsonArray.length(); idx++) {
JSONObject jsonObj = jsonArray.getJSONObject(idx);
values.add(jsonObj.optString(key));
}
return values;
}
public List<String> getValuesByKeyInJSONArrayUsingJava8(String jsonArrayStr, String key) {
JSONArray jsonArray = new JSONArray(jsonArrayStr);
return IntStream.range(0, jsonArray.length())
.mapToObj(index -> ((JSONObject) jsonArray.get(index)).optString(key))
.collect(Collectors.toList());
}
}
@@ -0,0 +1,46 @@
package com.baeldung.jsonjava;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public class JSONObjectDemo {
public static void main(String[] args) {
System.out.println("4.1. Creating JSONObject: ");
jsonFromJSONObject();
System.out.println("\n4.2. Creating JSONObject from Map: ");
jsonFromMap();
System.out.println("\n4.3. Creating JSONObject from JSON string: ");
jsonFromJSONString();
}
public static void jsonFromJSONObject() {
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
System.out.println(jo.toString());
}
public static void jsonFromMap() {
Map<String, String> map = new HashMap<>();
map.put("name", "jon doe");
map.put("age", "22");
map.put("city", "chicago");
JSONObject jo = new JSONObject(map);
System.out.println(jo.toString());
}
public static void jsonFromJSONString() {
JSONObject jo = new JSONObject(
"{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}"
);
System.out.println(jo.toString());
}
}
@@ -0,0 +1,13 @@
package com.baeldung.jsonjava;
import org.json.JSONTokener;
public class JSONTokenerDemo {
public static void main(String[] args) {
JSONTokener jt = new JSONTokener("Sample String");
while(jt.more()) {
System.out.println(jt.next());
}
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jsonjava;
import org.json.JSONObject;
public class ObjectToFromJSON {
public static void main(String args[]) throws Exception {
System.out.println("\n5.1. Creating JSONObject from Java Bean: ");
jsonFromDemoBean();
}
public static void jsonFromDemoBean() {
DemoBean demo = new DemoBean();
demo.setId(1);
demo.setName("lorem ipsum");
demo.setActive(true);
JSONObject jo = new JSONObject(demo);
System.out.println(jo);
}
}
@@ -0,0 +1,50 @@
package com.baeldung.jsonobject.iterate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONObjectIterator {
private Map<String, Object> keyValuePairs;
public JSONObjectIterator() {
keyValuePairs = new HashMap<>();
}
public void handleValue(String key, Object value) {
if (value instanceof JSONArray) {
handleJSONArray(key, (JSONArray) value);
} else if (value instanceof JSONObject) {
handleJSONObject((JSONObject) value);
}
keyValuePairs.put(key, value);
}
public void handleJSONObject(JSONObject jsonObject) {
Iterator<String> jsonObjectIterator = jsonObject.keys();
jsonObjectIterator.forEachRemaining(key -> {
Object value = jsonObject.get(key);
handleValue(key, value);
});
}
public void handleJSONArray(String key, JSONArray jsonArray) {
Iterator<Object> jsonArrayIterator = jsonArray.iterator();
jsonArrayIterator.forEachRemaining(element -> {
handleValue(key, element);
});
}
public Map<String, Object> getKeyValuePairs() {
return keyValuePairs;
}
public void setKeyValuePairs(Map<String, Object> keyValuePairs) {
this.keyValuePairs = keyValuePairs;
}
}
@@ -0,0 +1,95 @@
package com.baeldung.jsonpointer;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonPointer;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonStructure;
public class JsonPointerCrud {
private JsonStructure jsonStructure = null;
public JsonPointerCrud(String fileName) throws IOException {
try (JsonReader reader = Json.createReader(Files.newBufferedReader(Paths.get(fileName)))) {
jsonStructure = reader.read();
} catch (FileNotFoundException e) {
System.out.println("Error to open json file: " + e.getMessage());
}
}
public JsonPointerCrud(InputStream stream) {
JsonReader reader = Json.createReader(stream);
jsonStructure = reader.read();
reader.close();
}
public JsonStructure insert(String key, String value) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonValue = Json.createValue(value);
jsonStructure = jsonPointer.add(jsonStructure, jsonValue);
return jsonStructure;
}
public JsonStructure update(String key, String newValue) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonNewValue = Json.createValue(newValue);
jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue);
return jsonStructure;
}
public JsonStructure delete(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
jsonPointer.getValue(jsonStructure);
jsonStructure = jsonPointer.remove(jsonStructure);
return jsonStructure;
}
public String fetchValueFromKey(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure);
return jsonString.getString();
}
public String fetchListValues(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString();
}
public String fetchFullJSON() {
JsonPointer jsonPointer = Json.createPointer("");
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString();
}
public boolean check(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
boolean found = jsonPointer.containsValue(jsonStructure);
return found;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
+27
View File
@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html ng-app="jsonforms-intro">
<head>
<title>Introduction to JSONForms</title>
<script src="node_modules/jsonforms/dist/jsonforms.js" type="text/javascript"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/schema.js" type="text/javascript"></script>
<script src="js/ui-schema.js" type="text/javascript"></script>
</head>
<body>
<div class="container" ng-controller="MyController">
<div class="row" id="demo">
<div class="col-sm-12">
<div class="panel-primary panel-default">
<div class="panel-heading">
<h3 class="panel-title"><strong>Introduction to JSONForms</strong></h3>
</div>
<div class="panel-body jsf">
Bound data: {{data}}
<jsonforms schema="schema" ui-schema="uiSchema" data="data"/>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
'use strict';
var app = angular.module('jsonforms-intro', ['jsonforms']);
app.controller('MyController', ['$scope', 'Schema', 'UISchema', function($scope, Schema, UISchema) {
$scope.schema = Schema;
$scope.uiSchema = UISchema;
$scope.data = {
"id": 1,
"name": "Lampshade",
"price": 1.85
};
}]);
+27
View File
@@ -0,0 +1,27 @@
'use strict';
var app = angular.module('jsonforms-intro');
app.value('Schema',
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from the catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": ["id", "name", "price"]
}
);
+22
View File
@@ -0,0 +1,22 @@
'use strict';
var app = angular.module('jsonforms-intro');
app.value('UISchema',
{
"type": "HorizontalLayout",
"elements": [
{
"type": "Control",
"scope": { "$ref": "#/properties/id" }
},
{
"type": "Control",
"scope": { "$ref": "#/properties/name" }
},
{
"type": "Control",
"scope": { "$ref": "#/properties/price" }
},
]
}
);
+11
View File
@@ -0,0 +1,11 @@
{
"name": "jsonforms-intro",
"description": "Introduction to JSONForms",
"version": "0.0.1",
"license": "MIT",
"dependencies": {
"typings": "0.6.5",
"jsonforms": "0.0.19",
"bootstrap": "3.3.6"
}
}
@@ -0,0 +1,36 @@
package com.baeldung.escape;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class JsonEscapeUnitTest {
private JsonEscape testedInstance;
private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}";
@BeforeEach
void setUp() {
testedInstance = new JsonEscape();
}
@Test
void escapeJson() {
String actual = testedInstance.escapeJson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
@Test
void escapeGson() {
String actual = testedInstance.escapeGson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
@Test
void escapeJackson() throws JsonProcessingException {
String actual = testedInstance.escapeJackson("Hello \"World\"");
assertEquals(EXPECTED, actual);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.json.schema;
import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.Test;
public class JSONSchemaUnitTest {
@Test(expected = ValidationException.class)
public void givenInvalidInput_whenValidating_thenInvalid() {
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_invalid.json")));
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonSubject);
}
@Test
public void givenValidInput_whenValidating_thenValid() {
JSONObject jsonSchema = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")));
JSONObject jsonSubject = new JSONObject(new JSONTokener(JSONSchemaUnitTest.class.getResourceAsStream("/product_valid.json")));
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonSubject);
}
}
@@ -0,0 +1,189 @@
package com.baeldung.jsonb;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;
import javax.json.bind.config.PropertyNamingStrategy;
import javax.json.bind.config.PropertyOrderStrategy;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.baeldung.adapter.PersonAdapter;
import com.baeldung.jsonb.Person;
public class JsonbUnitTest {
@Test
public void givenPersonList_whenSerializeWithJsonb_thenGetPersonJsonArray() {
Jsonb jsonb = JsonbBuilder.create();
// @formatter:off
List<Person> personList = Arrays.asList(
new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)));
// @formatter:on
String jsonArrayPerson = jsonb.toJson(personList);
// @formatter:off
String jsonExpected = "[" +
"{\"email\":\"jhon@test.com\"," +
"\"id\":1,\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1000.0\"}," +
"{\"email\":\"jhon1@test.com\"," +
"\"id\":2,\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1500.0\"},{\"email\":null," +
"\"id\":3,\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1000.0\"}," +
"{\"email\":\"tom@test.com\"," +
"\"id\":4,\"person-name\":\"Tom\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1500.0\"}"
+ "]";
// @formatter:on
assertTrue(jsonArrayPerson.equals(jsonExpected));
}
@Test
public void givenPersonJsonArray_whenDeserializeWithJsonb_thenGetPersonList() {
Jsonb jsonb = JsonbBuilder.create();
// @formatter:off
String personJsonArray =
"[" +
"{\"email\":\"jhon@test.com\"," +
"\"id\":1,\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1000.0\"}," +
"{\"email\":\"jhon1@test.com\"," +
"\"id\":2,\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1500.0\"},{\"email\":null," +
"\"id\":3,\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1000.0\"}," +
"{\"email\":\"tom@test.com\"," +
"\"id\":4,\"person-name\":\"Tom\"," +
"\"registeredDate\":\"09-09-2019\"," +
"\"salary\":\"1500.0\"}"
+ "]";
// @formatter:on
@SuppressWarnings("serial")
List<Person> personList = jsonb.fromJson(personJsonArray, new ArrayList<Person>() {
}.getClass()
.getGenericSuperclass());
// @formatter:off
List<Person> personListExpected = Arrays.asList(
new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(2, "Jhon", "jhon1@test.com", 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)),
new Person(3, "Jhon", null, 20, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1000)),
new Person(4, "Tom", "tom@test.com", 21, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500)));
// @formatter:on
assertTrue(ListUtils.isEqualList(personList, personListExpected));
}
@Test
public void givenPersonObject_whenNamingStrategy_thenGetCustomPersonJson() {
JsonbConfig config = new JsonbConfig().withPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES);
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
String jsonPerson = jsonb.toJson(person);
// @formatter:off
String jsonExpected =
"{\"email\":\"jhon@test.com\"," +
"\"id\":1," +
"\"person-name\":\"Jhon\"," +
"\"registered_date\":\"07-09-2019\"," +
"\"salary\":\"1000.0\"}";
// @formatter:on
assertTrue(jsonExpected.equals(jsonPerson));
}
@Test
public void givenPersonObject_whenWithPropertyOrderStrategy_thenGetReversePersonJson() {
JsonbConfig config = new JsonbConfig().withPropertyOrderStrategy(PropertyOrderStrategy.REVERSE);
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
String jsonPerson = jsonb.toJson(person);
// @formatter:off
String jsonExpected =
"{\"salary\":\"1000.0\","+
"\"registeredDate\":\"07-09-2019\"," +
"\"person-name\":\"Jhon\"," +
"\"id\":1," +
"\"email\":\"jhon@test.com\"}";
// @formatter:on
assertTrue(jsonExpected.equals(jsonPerson));
}
@Test
public void givenPersonObject_whenSerializeWithJsonb_thenGetPersonJson() {
Jsonb jsonb = JsonbBuilder.create();
Person person = new Person(1, "Jhon", "jhon@test.com", 20, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000));
String jsonPerson = jsonb.toJson(person);
// @formatter:off
String jsonExpected =
"{\"email\":\"jhon@test.com\"," +
"\"id\":1," +
"\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"07-09-2019\"," +
"\"salary\":\"1000.0\"}";
// @formatter:on
assertTrue(jsonExpected.equals(jsonPerson));
}
@Test
public void givenPersonJson_whenDeserializeWithJsonb_thenGetPersonObject() {
Jsonb jsonb = JsonbBuilder.create();
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));
// @formatter:off
String jsonPerson =
"{\"email\":\"jhon@test.com\"," +
"\"id\":1," +
"\"person-name\":\"Jhon\"," +
"\"registeredDate\":\"07-09-2019\"," +
"\"salary\":\"1000.0\"}";
// @formatter:on
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
.equals(person));
}
@Test
public void givenPersonObject_whenSerializeWithAdapter_thenGetPersonJson() {
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
String jsonPerson = jsonb.toJson(person);
// @formatter:off
String jsonExpected =
"{\"id\":1," +
"\"name\":\"Jhon\"}";
// @formatter:on
assertTrue(jsonExpected.equals(jsonPerson));
}
@Test
public void givenPersonJson_whenDeserializeWithAdapter_thenGetPersonObject() {
JsonbConfig config = new JsonbConfig().withAdapters(new PersonAdapter());
Jsonb jsonb = JsonbBuilder.create(config);
Person person = new Person(1, "Jhon", "jhon@test.com", 0, LocalDate.of(2019, 9, 7), BigDecimal.valueOf(1000.0));// new Person(1, "Jhon");
// @formatter:off
String jsonPerson =
"{\"id\":1," +
"\"name\":\"Jhon\"}";
// @formatter:on
assertTrue(jsonb.fromJson(jsonPerson, Person.class)
.equals(person));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;
import org.junit.Test;
public class CDLIntegrationTest {
@Test
public void givenCommaDelimitedText_thenConvertToJSONArray() {
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
assertEquals("[\"England\",\"USA\",\"Canada\"]", ja.toString());
}
@Test
public void givenJSONArray_thenConvertToCommaDelimitedText() {
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);
assertEquals("England,USA,Canada", cdt.toString().trim());
}
@Test
public void givenCommaDelimitedText_thenGetJSONArrayOfJSONObjects() {
String string =
"name, city, age \n" +
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(string);
assertEquals("[{\"name\":\"john\",\"city\":\"chicago\",\"age\":\"22\"},{\"name\":\"gary\",\"city\":\"florida\",\"age\":\"35\"},{\"name\":\"sal\",\"city\":\"vegas\",\"age\":\"18\"}]", result.toString());
}
@Test
public void givenCommaDelimitedText_thenGetJSONArrayOfJSONObjects2() {
JSONArray ja = new JSONArray();
ja.put("name");
ja.put("city");
ja.put("age");
String string =
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(ja, string);
assertEquals("[{\"name\":\"john\",\"city\":\"chicago\",\"age\":\"22\"},{\"name\":\"gary\",\"city\":\"florida\",\"age\":\"35\"},{\"name\":\"sal\",\"city\":\"vegas\",\"age\":\"18\"}]", result.toString());
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.Cookie;
import org.json.JSONObject;
import org.junit.Test;
public class CookieIntegrationTest {
@Test
public void givenCookieString_thenConvertToJSONObject() {
String cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
JSONObject cookieJO = Cookie.toJSONObject(cookie);
assertEquals("{\"path\":\"/\",\"expires\":\"Thu, 18 Dec 2013 12:00:00 UTC\",\"name\":\"username\",\"value\":\"John Doe\"}", cookieJO.toString());
}
@Test
public void givenJSONObject_thenConvertToCookieString() {
JSONObject cookieJO = new JSONObject();
cookieJO.put("name", "username");
cookieJO.put("value", "John Doe");
cookieJO.put("expires", "Thu, 18 Dec 2013 12:00:00 UTC");
cookieJO.put("path", "/");
String cookie = Cookie.toString(cookieJO);
assertEquals("username=John Doe;expires=Thu, 18 Dec 2013 12:00:00 UTC;path=/", cookie.toString());
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.HTTP;
import org.json.JSONObject;
import org.junit.Test;
public class HTTPIntegrationTest {
@Test
public void givenJSONObject_thenConvertToHTTPHeader() {
JSONObject jo = new JSONObject();
jo.put("Method", "POST");
jo.put("Request-URI", "http://www.example.com/");
jo.put("HTTP-Version", "HTTP/1.1");
assertEquals("POST \"http://www.example.com/\" HTTP/1.1"+HTTP.CRLF+HTTP.CRLF, HTTP.toString(jo));
}
@Test
public void givenHTTPHeader_thenConvertToJSONObject() {
JSONObject obj = HTTP.toJSONObject("POST \"http://www.example.com/\" HTTP/1.1");
assertEquals("{\"Request-URI\":\"http://www.example.com/\",\"Method\":\"POST\",\"HTTP-Version\":\"HTTP/1.1\"}", obj.toString());
}
}
@@ -0,0 +1,35 @@
package com.baeldung.jsonjava;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
public class JSONArrayGetValueByKeyUnitTest {
private static final JSONArrayGetValueByKey obj = new JSONArrayGetValueByKey();
@Test
public void givenJSONArrayAndAKey_thenReturnAllValuesForGivenKey() {
String jsonStr = "[" + " {" + " \"name\": \"John\"," + " \"city\": \"chicago\"," + " \"age\": \"22\" " + "}," + " { " + "\"name\": \"Gary\"," + " \"city\": \"florida\"," + " \"age\": \"35\" " + "}," + " { " + "\"name\": \"Selena\","
+ " \"city\": \"vegas\"," + " \"age\": \"18\" " + "} " + "]";
List<String> actualValues = obj.getValuesByKeyInJSONArray(jsonStr, "name");
assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena")));
}
@Test
public void givenJSONArrayAndAKey_whenUsingJava8Syntax_thenReturnAllValuesForGivenKey() {
String jsonStr = "[" + " {" + " \"name\": \"John\"," + " \"city\": \"chicago\"," + " \"age\": \"22\" " + "}," + " { " + "\"name\": \"Gary\"," + " \"city\": \"florida\"," + " \"age\": \"35\" " + "}," + " { " + "\"name\": \"Selena\","
+ " \"city\": \"vegas\"," + " \"age\": \"18\" " + "} " + "]";
List<String> actualValues = obj.getValuesByKeyInJSONArrayUsingJava8(jsonStr, "name");
assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena")));
}
}
@@ -0,0 +1,47 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class JSONArrayIntegrationTest {
@Test
public void givenJSONJava_thenCreateNewJSONArrayFromScratch() {
JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");
// We can also put a JSONObject in JSONArray
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
ja.put(jo);
assertEquals("[true,\"lorem ipsum\",{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}]", ja.toString());
}
@Test
public void givenJsonString_thenCreateNewJSONArray() {
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
assertEquals("[true,\"lorem ipsum\",215]", ja.toString());
}
@Test
public void givenListObject_thenConvertItToJSONArray() {
List<String> list = new ArrayList<>();
list.add("California");
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");
JSONArray ja = new JSONArray(list);
assertEquals("[\"California\",\"Texas\",\"Hawaii\",\"Alaska\"]", ja.toString());
}
}
@@ -0,0 +1,42 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.junit.Test;
public class JSONObjectIntegrationTest {
@Test
public void givenJSONJava_thenCreateNewJSONObject() {
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
assertEquals("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}", jo.toString());
}
@Test
public void givenMapObject_thenCreateJSONObject() {
Map<String, String> map = new HashMap<>();
map.put("name", "jon doe");
map.put("age", "22");
map.put("city", "chicago");
JSONObject jo = new JSONObject(map);
assertEquals("{\"name\":\"jon doe\",\"city\":\"chicago\",\"age\":\"22\"}", jo.toString());
}
@Test
public void givenJsonString_thenCreateJSONObject() {
JSONObject jo = new JSONObject(
"{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}"
);
assertEquals("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}", jo.toString());
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.JSONTokener;
import org.junit.Test;
public class JSONTokenerIntegrationTest {
@Test
public void givenString_convertItToJSONTokens() {
String str = "Sample String";
JSONTokener jt = new JSONTokener(str);
char[] expectedTokens = str.toCharArray();
int index = 0;
while(jt.more()) {
assertEquals(expectedTokens[index++], jt.next());
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.JSONObject;
import org.junit.Test;
public class ObjectToFromJSONIntegrationTest {
@Test
public void givenDemoBean_thenCreateJSONObject() {
DemoBean demo = new DemoBean();
demo.setId(1);
demo.setName("lorem ipsum");
demo.setActive(true);
JSONObject jo = new JSONObject(demo);
assertEquals("{\"name\":\"lorem ipsum\",\"active\":true,\"id\":1}", jo.toString());
}
}
@@ -0,0 +1,79 @@
package com.baeldung.jsonobject.iterate;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class JSONObjectIteratorUnitTest {
private JSONObjectIterator jsonObjectIterator = new JSONObjectIterator();
@Test
public void givenJSONObject_whenIterating_thenGetKeyValuePairs() {
JSONObject jsonObject = getJsonObject();
jsonObjectIterator.handleJSONObject(jsonObject);
Map<String, Object> keyValuePairs = jsonObjectIterator.getKeyValuePairs();
assertThat(keyValuePairs.get("rType")).isEqualTo("Regular");
assertThat(keyValuePairs.get("rId")).isEqualTo("1001");
assertThat(keyValuePairs.get("cType")).isEqualTo("Chocolate");
assertThat(keyValuePairs.get("cId")).isEqualTo("1002");
assertThat(keyValuePairs.get("bType")).isEqualTo("BlueBerry");
assertThat(keyValuePairs.get("bId")).isEqualTo("1003");
assertThat(keyValuePairs.get("name")).isEqualTo("Cake");
assertThat(keyValuePairs.get("cakeId")).isEqualTo("0001");
assertThat(keyValuePairs.get("type")).isEqualTo("donut");
assertThat(keyValuePairs.get("Type")).isEqualTo("Maple");
assertThat(keyValuePairs.get("tId")).isEqualTo("5001");
assertThat(keyValuePairs.get("batters")
.toString()).isEqualTo("[{\"rType\":\"Regular\",\"rId\":\"1001\"},{\"cType\":\"Chocolate\",\"cId\":\"1002\"},{\"bType\":\"BlueBerry\",\"bId\":\"1003\"}]");
assertThat(keyValuePairs.get("cakeShapes")
.toString()).isEqualTo("[\"square\",\"circle\",\"heart\"]");
assertThat(keyValuePairs.get("topping")
.toString()).isEqualTo("{\"Type\":\"Maple\",\"tId\":\"5001\"}");
}
private JSONObject getJsonObject() {
JSONObject cake = new JSONObject();
cake.put("cakeId", "0001");
cake.put("type", "donut");
cake.put("name", "Cake");
JSONArray batters = new JSONArray();
JSONObject regular = new JSONObject();
regular.put("rId", "1001");
regular.put("rType", "Regular");
batters.put(regular);
JSONObject chocolate = new JSONObject();
chocolate.put("cId", "1002");
chocolate.put("cType", "Chocolate");
batters.put(chocolate);
JSONObject blueberry = new JSONObject();
blueberry.put("bId", "1003");
blueberry.put("bType", "BlueBerry");
batters.put(blueberry);
JSONArray cakeShapes = new JSONArray();
cakeShapes.put("square");
cakeShapes.put("circle");
cakeShapes.put("heart");
cake.put("cakeShapes", cakeShapes);
cake.put("batters", batters);
JSONObject topping = new JSONObject();
topping.put("tId", "5001");
topping.put("Type", "Maple");
cake.put("topping", topping);
return cake;
}
}
@@ -0,0 +1,59 @@
package com.baeldung.jsonpointer;
import static org.junit.Assert.*;
import org.junit.Test;
public class JsonPointerCrudUnitTest {
@Test
public void testJsonPointerCrudForAddress() {
JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/address.json"));
assertFalse(jsonPointerCrud.check("city"));
// insert a value
jsonPointerCrud.insert("city", "Rio de Janeiro");
assertTrue(jsonPointerCrud.check("city"));
// fetch full json
String fullJSON = jsonPointerCrud.fetchFullJSON();
assertTrue(fullJSON.contains("name"));
assertTrue(fullJSON.contains("city"));
// fetch value
String cityName = jsonPointerCrud.fetchValueFromKey("city");
assertEquals(cityName, "Rio de Janeiro");
// update value
jsonPointerCrud.update("city", "Sao Paulo");
// fetch value
cityName = jsonPointerCrud.fetchValueFromKey("city");
assertEquals(cityName, "Sao Paulo");
// delete
jsonPointerCrud.delete("city");
assertFalse(jsonPointerCrud.check("city"));
}
@Test
public void testJsonPointerCrudForBooks() {
JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/books.json"));
// fetch value
String book = jsonPointerCrud.fetchListValues("books/1");
assertEquals(book, "{\"title\":\"Title 2\",\"author\":\"John Doe\"}");
}
}
@@ -0,0 +1,95 @@
package fast_json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BeanContext;
import com.alibaba.fastjson.serializer.ContextValueFilter;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.SerializeConfig;
import org.junit.Before;
import org.junit.Test;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class FastJsonUnitTest {
private List<Person> listOfPersons;
@Before
public void setUp() {
listOfPersons = new ArrayList<Person>();
Calendar calendar = Calendar.getInstance();
calendar.set(2016, 6, 24);
listOfPersons.add(new Person(15, "John", "Doe", calendar.getTime()));
listOfPersons.add(new Person(20, "Janette", "Doe", calendar.getTime()));
}
@Test
public void whenJavaList_thanConvertToJsonCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons);
assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]");
}
@Test
public void whenJson_thanConvertToObjectCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
assertEquals(newPerson.getFirstName(), listOfPersons.get(0)
.getFirstName());
assertEquals(newPerson.getLastName(), listOfPersons.get(0)
.getLastName());
}
@Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("FIRST NAME", "John" + i);
jsonObject.put("LAST NAME", "Doe" + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
}
@Test
public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
ContextValueFilter valueFilter = new ContextValueFilter() {
public Object process(BeanContext context, Object object, String name, Object value) {
if (name.equals("DATE OF BIRTH")) {
return "NOT TO DISCLOSE";
}
if (value.equals("John") || value.equals("Doe")) {
return ((String) value).toUpperCase();
} else {
return null;
}
}
};
JSON.toJSONString(listOfPersons, valueFilter);
}
@Test
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
NameFilter formatName = new NameFilter() {
public String process(Object object, String name, Object value) {
return name.toLowerCase()
.replace(" ", "_");
}
};
SerializeConfig.getGlobalInstance()
.addFilter(Person.class, formatName);
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
// resetting custom serializer
SerializeConfig.getGlobalInstance()
.put(Person.class, null);
}
}
+69
View File
@@ -0,0 +1,69 @@
package fast_json;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;
public class Person {
@JSONField(name = "AGE", serialize = false, deserialize = false)
private int age;
@JSONField(name = "LAST NAME", ordinal = 2)
private String lastName;
@JSONField(name = "FIRST NAME", ordinal = 1)
private String firstName;
@JSONField(name = "DATE OF BIRTH", format = "dd/MM/yyyy", ordinal = 3)
private Date dateOfBirth;
public Person() {
}
public Person(int age, String lastName, String firstName, Date dateOfBirth) {
super();
this.age = age;
this.lastName = lastName;
this.firstName = firstName;
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]";
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"name": "Customer 01",
"street name": "Street 01"
}
+7
View File
@@ -0,0 +1,7 @@
{
"library": "My Personal Library",
"books": [
{ "title":"Title 1", "author":"Jane Doe" },
{ "title":"Title 2", "author":"John Doe" }
]
}
@@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 0
}
@@ -0,0 +1,5 @@
{
"id": 1,
"name": "Lampshade",
"price": 10
}
+22
View File
@@ -0,0 +1,22 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from the catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": ["id", "name", "price"]
}