Skip to content

Commit

Permalink
added JSON support (#53) (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
mariodavid committed Apr 29, 2018
1 parent 60d20af commit 8d7a3b2
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 0 deletions.
10 changes: 10 additions & 0 deletions example-data/roles.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[
{
"Name": "Users",
"Description": "The users of the system"
},
{
"Name": "Moderators",
"Description": "The mods of the system"
}
]
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class DataConverterFactory {
switch (fileDescriptor.extension) {
case 'xlsx': return new ExcelImportDataConverter()
case 'csv': return new CsvImportDataConverter()
case 'json': return new JsonImportDataConverter()
case 'xml': return new XmlImportDataConverter()
default: throw new FileNotSupportedException()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package de.diedavids.cuba.dataimport.converter

import de.diedavids.cuba.dataimport.dto.DataRow
import de.diedavids.cuba.dataimport.dto.DataRowImpl
import de.diedavids.cuba.dataimport.dto.ImportData
import de.diedavids.cuba.dataimport.dto.ImportDataImpl
import groovy.json.JsonSlurper

class JsonImportDataConverter implements ImportDataConverter {
@Override
ImportData convert(String content) {
def result = new ImportDataImpl()

def json = parseJson(content)

json.each {
result.columns = getColumns(it)
addToTableData(result, it)
}

result
}

private Object parseJson(String content) {
new JsonSlurper().parseText(content)
}

private List<String> getColumns(it) {
new ArrayList(it.keySet())
}

private DataRow addToTableData(ImportDataImpl importData, Map row) {
def dataRow = DataRowImpl.ofMap(row)
importData.rows << dataRow
dataRow
}

@Override
ImportData convert(File file) {
convert(file.text)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package de.diedavids.cuba.dataimport.converter

import de.diedavids.cuba.dataimport.dto.ImportData
import spock.lang.Specification

class JsonImportDataConverterSpec extends Specification {
private sut
private String JSON_STRING = '''[
{
"Name": "Mark",
"Lastname": "Andersson"
},
{
"Name": "Pete",
"Lastname": "Hansen"
}
]'''


void setup() {
sut = new JsonImportDataConverter()
}

def "convert contains the correct amount of columns"() {

when:
ImportData result = sut.convert(JSON_STRING)
then:
result.columns.size() == 2
}

def "convert contains two DataRows"() {
when:
ImportData result = sut.convert(JSON_STRING)
then:
result.rows.size() == 2
}

def "convert contains the correct values for the DataRows"() {
when:
ImportData result = sut.convert(JSON_STRING)
then:
result.rows[0].Name == 'Mark'
result.rows[0].Lastname == 'Andersson'
}
}

0 comments on commit 8d7a3b2

Please sign in to comment.