Test `JsonGenerator`

This commit is contained in:
Alex Golub 2023-01-14 18:11:19 +02:00
parent 85775f930a
commit ab5c09a958
1 changed files with 43 additions and 15 deletions

View File

@ -1,5 +1,6 @@
package com.baeldung.json package com.baeldung.json
import groovy.json.JsonGenerator
import spock.lang.Specification import spock.lang.Specification
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
@ -8,20 +9,42 @@ class JsonParserTest extends Specification {
JsonParser jsonParser JsonParser jsonParser
void setup () { void setup() {
jsonParser = new JsonParser() jsonParser = new JsonParser()
} }
def 'Should parse to Account given Json String' () { def 'Should parse to Account given Json String'() {
given: given:
def json = '{"id":"1234","value":15.6}' def json = '{"id":"1234","value":15.6}'
when: when:
def account = jsonParser.toObject(json) def account = jsonParser.toObject(json)
then: then:
account account
account instanceof Account account instanceof Account
account.id == '1234' account.id == '1234'
account.value == 15.6 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' () { /*def 'Should parse to Account given Json String with date property' () {
@ -52,15 +75,20 @@ class JsonParserTest extends Specification {
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}' 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: given:
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
when: when:
def jsonPretty = jsonParser.prettyfy(json) def jsonPretty = jsonParser.prettyfy(json)
then: then:
jsonPretty 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"
}'''
} }
} }