Test `JsonGenerator`
This commit is contained in:
parent
85775f930a
commit
ab5c09a958
|
@ -1,5 +1,6 @@
|
|||
package com.baeldung.json
|
||||
|
||||
import groovy.json.JsonGenerator
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.text.SimpleDateFormat
|
||||
|
@ -8,15 +9,17 @@ class JsonParserTest extends Specification {
|
|||
|
||||
JsonParser jsonParser
|
||||
|
||||
void setup () {
|
||||
void setup() {
|
||||
jsonParser = new JsonParser()
|
||||
}
|
||||
|
||||
def 'Should parse to Account given Json String' () {
|
||||
def 'Should parse to Account given Json String'() {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6}'
|
||||
|
||||
when:
|
||||
def account = jsonParser.toObject(json)
|
||||
|
||||
then:
|
||||
account
|
||||
account instanceof Account
|
||||
|
@ -24,6 +27,26 @@ class JsonParserTest extends Specification {
|
|||
account.value == 15.6
|
||||
}
|
||||
|
||||
def 'Should format date and exclude value field'() {
|
||||
given:
|
||||
def account = new Account(
|
||||
id: '123',
|
||||
value: 15.6,
|
||||
createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('14/01/2023')
|
||||
)
|
||||
|
||||
def jsonGenerator = new JsonGenerator.Options()
|
||||
.dateFormat('MM/dd/yyyy')
|
||||
.excludeFieldsByName('value')
|
||||
.build()
|
||||
|
||||
when:
|
||||
def accountToJson = jsonGenerator.toJson(account)
|
||||
|
||||
then:
|
||||
accountToJson == '{"createdAt":"01/31/2024","id":"123"}'
|
||||
}
|
||||
|
||||
/*def 'Should parse to Account given Json String with date property' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
|
||||
|
@ -52,15 +75,20 @@ class JsonParserTest extends Specification {
|
|||
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
|
||||
}*/
|
||||
|
||||
def 'Should prettify given a json string' () {
|
||||
def 'Should prettify given a json string'() {
|
||||
given:
|
||||
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
|
||||
|
||||
when:
|
||||
def jsonPretty = jsonParser.prettyfy(json)
|
||||
|
||||
then:
|
||||
jsonPretty
|
||||
jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}'
|
||||
jsonPretty == '''\
|
||||
{
|
||||
"value": 15.6,
|
||||
"createdAt": "01/01/2018",
|
||||
"id": "123456"
|
||||
}'''
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue