Skip to content

Instantly share code, notes, and snippets.

@stephenhardy
Created January 29, 2014 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenhardy/8679353 to your computer and use it in GitHub Desktop.
Save stephenhardy/8679353 to your computer and use it in GitHub Desktop.
@Grab(group = 'com.fasterxml.jackson.dataformat', module= 'jackson-dataformat-csv', version = '2.3.0')
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonPropertyOrder
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.dataformat.csv.CsvMapper
import com.fasterxml.jackson.dataformat.csv.CsvSchema
import com.fasterxml.jackson.databind.MappingIterator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectWriter
import com.fasterxml.jackson.databind.SerializationFeature
USAGE = "usage: csvToGroovy.groovy source_csv_file target_json_file"
if (!args || args.length < 2) {
println USAGE
return
}
csvFile = args[0]
outputFile = args[1]
CsvMapper mapper = new CsvMapper()
CsvSchema schema = CsvSchema.emptySchema().withHeader()
MappingIterator<Candle> it = mapper.reader(Candle).with(schema).readValues(new File(csvFile))
ObjectWriter ow = new ObjectMapper().writer().without(SerializationFeature.FAIL_ON_EMPTY_BEANS)
File out = new File(outputFile)
if (out.exists()){
out.delete()
}
while (it.hasNext()){
row = it.next()
out.append(ow.writeValueAsString(row))
if (it.hasNext()) {
out.append("\n")
}
}
/**
* POJO to hold the time series data
*/
class Candle {
@JsonCreator
public Candle( @JsonProperty("date") String date,
@JsonProperty("ticker") String ticker,
@JsonProperty("open") String open,
@JsonProperty("high") String high,
@JsonProperty("low") String low,
@JsonProperty("close") String close,
@JsonProperty("volume") String volume) {
this.date = date
this.ticker = ticker
this.open = open
this.high = high
this.low = low
this.close = close
this.volume = volume
}
@JsonProperty("date")
String date
@JsonProperty("ticker")
String ticker
@JsonProperty("open")
String open
@JsonProperty("high")
String high
@JsonProperty("low")
String low
@JsonProperty("close")
String close
@JsonProperty("volume")
String volume
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment