Foreword
Json format is used to develop information exchange web format specification simple, easy to understand the generated content.
Groovy support for Json is quite rich, here we take a look at how to use Groovy to complete common Json string parsing (serialization) and inverse solution (deserialization) task.
1. Several methods of generating sequence json
From simple to complex, followed by "with JsonOutput", "with JsonBuilder", "with JsonStreamBuilder" method, and the use of Java Json library tools, such as FastJson generation.
1.1 Json string generated by JsonOutput
When we have an object, it needs to be serialized to json string, we can write
ComplexClass object = new ComplexClass()
String jsonString = JsonOutput.toJson(object)
Very simple, but we can also make a class with toJson () method Category method.
use(JsonOutput) {
ComplexClass object = new ComplexClass()
ComplexClass2 object2 = new ComplexClass2()
String jsonString = object.toJson()
String jsonString2 = object2.toJson()
}
1.2 JsonGenerator with more flexible string generated Json
If we do not want to let some of the properties appear in the json string, you can write
class TenantStaff {
String userName
String password
Date dateCreated
Date lastUpdated
StringProperty elementNameProperty
ObservableList children
}
def generator = new JsonGenerator.Options()
.excludeFieldsByName('elementNameProperty')
.excludeFieldsByType(Date, ObservableList)
.build()
String jsonString = generator.toJson(object)
assert generator.toJson(person) == '{"userName":"xxx","password":"xxx"}'
However, if we want to change the properties of the object name, or take the properties of an object attributes, then JsonGenerator is powerless, JsonBuilder need to achieve.
1.3 Json string generated by JsonBuilder
[TODO, are behind empty TODO]
1.4 Json string generated by JsonStreamBuilder
2. The analysis method Json string
2.1 Analytical Json string with JsonSlurper
2.2 GroovyObject json string obtained is converted to specific areas of the class
Analytical methods 2.3 json string with FastJson
Think
How can the solution during the anti-json string, more easily take advantage of DSL groovy ability to specify conversion rules specific property? Maybe we can develop a set of their own such as DSL.
This allows us to configure DSL and parse json string:
DomainClass complexObject = Json.parseRules {
prop.subProp.rule = new DateRule
prop2.rule = { new SpecialClass(it.value) }
}.parse(jsonString)