Java tutorial
/* * Copyright 2015 Robert von Burg <eitch@eitchnet.ch> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.eitchnet.csvrestendpoint.marshaller; import java.nio.charset.Charset; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import ch.eitchnet.csvrestendpoint.model.CsvQuery; import ch.eitchnet.csvrestendpoint.util.CsvFormatBuilder; import ch.eitchnet.utils.helper.StringHelper; /** * @author Robert von Burg <eitch@eitchnet.ch> */ public class CsvDataToHeaderJsonMarshaller implements CsvDataMarshaller<JsonObject> { private CSVFormat csvFormat; public Charset charset; public CsvDataToHeaderJsonMarshaller(CsvQuery query) { this.csvFormat = new CsvFormatBuilder(query).build(); if (StringHelper.isEmpty(query.getCharset())) this.charset = Charset.forName("UTF-8"); else this.charset = Charset.forName(query.getCharset()); } @Override public CSVFormat getCsvFormat() { return this.csvFormat; } @Override public Charset getCharset() { return this.charset; } @Override public JsonObject marshall(CSVParser csvParser) { JsonObject root = new JsonObject(); root.addProperty("msg", "-"); JsonArray data = new JsonArray(); Set<Entry<String, Integer>> header = csvParser.getHeaderMap().entrySet(); for (Entry<String, Integer> entry : header) { data.add(new JsonPrimitive(entry.getKey())); } root.add("data", data); return root; } }