Gson Parse Json with List<String> - java

I have a class with some fields:
public class GsonRepro {
class A {
private List<String> field1 = new ArrayList<>();
private String name;
private Integer status;
public A(){
}
public List<String> getfield1() { return field1; }
public void setField1(List<String> field1) { this.field1 = field1; }
public String getName() { return name; }
public void setName() { this.name = name; }
public Integer getStatus() { return status; }
public void setStatus(int status) { this.status = status; }
}
public static void main(String[] args) {
String str = "{\"name\":\"my-name-1\",\"status\":0,\"field1\":[\"0eac6b1d3d494c2d8568cd82d9d13d5f\"]}";
A a = new Gson().fromJson(str, A.class);
}
}
All fields are parsed but the List<String> field1, how can I get this to work?
Solution:
The code above works just fine. Initially, I just had a typo in the List field.

I tried with the code as above that you shared and is working fine without any issues. Please check following code and verify,
public static void main(String[] args) {
String str = "{\"name\":\"my-name-1\",\"status\":0,\"field1\":[\"0eac6b1d3d494c2d8568cd82d9d13d5f\"]}";
A a = new Gson().fromJson(str, A.class);
System.out.println(a.getName());
System.out.println(a.getStatus());
System.out.println(a.getfield1());
}
Following is the output which is being printed on console as,
my-name-1
0
[0eac6b1d3d494c2d8568cd82d9d13d5f]

you can try to use TypeToken like in this answer to another question.
For you it would look like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...
Type type = new TypeToken<A>(){}.getType();
A a = new Gson().fromJson(str, type);
Greetings

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
class A {
private List<String> field1 = new ArrayList<>();
private String name;
private Integer status;
public A() {
}
public List<String> getfield1() {
return field1;
}
public void setField1(List<String> field1) {
this.field1 = field1;
}
public String getName() {
return name;
}
public void setName() {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
public class GsonParseList {
public static void main(String[] args) {
String str = "{'name':'my-name-1','status':0,'field1':['0eac6b1d3d494c2','d8568cd82d9d13d5f']}";
A a = new Gson().fromJson(str, A.class);
System.out.println(a.getfield1());
}
}

Related

Distinct the data model from ArraList to post the data to sever in android

My ArrayList is like the attached image.
So, I want to distinct the list and need to post the data to server.
So I have created the Serialized model class like
#SerializedName("VehicleList")
public List<VehicleList> vehicleList = new ArrayList<>();
public static class VehicleList {
#SerializedName("VehicleNumber")
public String vehicleNumber;
#SerializedName("Mileage")
public String mileage;
#SerializedName("Coupons")
public List<Coupons> coupons = new ArrayList<>();
}
public static class Coupons {
#SerializedName("Code")
public String code;
}
My ArrayList like this
List<CodeItem> mList = new ArrayList<CodeItem>();
code item look like this
public class CodeItem {
private String code;
private String status;
private String vehicleID;
private String mileage;
private String date;
public boolean selected;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVehicleID() {
return vehicleID;
}
public void setVehicleID(String vehicleID) {
this.vehicleID = vehicleID;
}
public String getMileage() {
return mileage;
}
public void setMileage(String mileage) {
this.mileage = mileage;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Now I want to distinct the data for vehicle id and post it to sever. So how do I distinct the data by VehicleID from this mList?
Thanks in advance

want to deserialize json string into java object with arraylist

java object: MyObject has a list of AnotherObject1 and AnotherObject1 also have a list of AnotherObject2
class MyObject{
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
Class AnotherObject1{
private Integer group_id;
private List<AnotherObject2> anotherList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getAnotherList() {
return smsList;
}
public void setAnotherList(List<AnotherObject2> anotherList) {
this.anotherList = anotherList;
}
}
class AnotherObject2{
private String customid;
private String customid1 ;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
JSON String: this is my json string by which i want to make an java object using object mapper
String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"
ObjectMapper code
//convert string to response object
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);
exception: here is the exception
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
at abc.disp(RestClientImpl.java:210)
at abc.disp(RestClientImpl.java:105)
at Application.<init>(Application.java:42)
at Application.main(Application.java:45)
please guide me how to make it possible.
Your code itself is not compailable ...
private List<AnotherObject1> data; // Your class member is list of AnotherObject1
and below it is used as List of SMSDTO in getter and setter
public List<SMSDTO> getData() {
return data;
}
Problem is quite simple: you claim data should become Java List; and this requires that JSON input for it should be JSON Array. But what JSON instead has is a JSON Object.
So you either need to change POJO definition to expect something compatible with JSON Object (a POJO or java.util.Map); or JSON to contain an array for data.
First as Naveen Ramawat said your code is not compilable as it is.
In the class AnotherObject1 getSmsList should take AnotherObject2 and setSmsList should take AnotherObject2 also as parameter.
In the class MyObject setData and getData should use AnotherObject1 as parameters
Second your JSON string is not valid it should be sommething like that:
{"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
Here is the code that I used :
MyObject.java:
import java.util.List;
class MyObject {
private String status;
private String message;
private List<AnotherObject1> data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<AnotherObject1> getData() {
return data;
}
public void setData(List<AnotherObject1> data) {
this.data = data;
}
}
AnotherObject1.java :
import java.util.List;
public class AnotherObject1 {
private Integer group_id;
private List<AnotherObject2> smsList;
public Integer getGroup_id() {
return group_id;
}
public void setGroup_id(Integer group_id) {
this.group_id = group_id;
}
public List<AnotherObject2> getSmsList() {
return smsList;
}
public void setSmsList(List<AnotherObject2> smsList) {
this.smsList = smsList;
}
}
AnotherObject2.java :
public class AnotherObject2 {
private String customid;
private String customid1;
private Long mobile;
private String status;
private String country;
public String getCustomid() {
return customid;
}
public void setCustomid(String customid) {
this.customid = customid;
}
public String getCustomid1() {
return customid1;
}
public void setCustomid1(String customid1) {
this.customid1 = customid1;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
To get the JSON string :
import org.json.JSONObject;
import org.json.XML;
import com.google.gson.Gson;
MyObject myObj = new MyObject();
ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
AnotherObject1 ao1 = new AnotherObject1();
ao1.setGroup_id(39545922);
ao1.setSmsList(smsList);
AnotherObject2 sms = new AnotherObject2();
sms.setCountry("XYZ");
sms.setCustomid("39545922-1");
sms.setCustomid1("");
sms.setMobile((long) 913456789);
sms.setStatus("XYZ");
smsList.add(sms);
ao1.setSmsList(smsList);
data.add(ao1);
myObj.setStatus("OK");
myObj.setData(data);
// Build a JSON string to display
Gson gson = new Gson();
String jsonString = gson.toJson(myObj);
System.out.println(jsonString);
// Get an object from a JSON string
MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
// Display the new object
System.out.println(gson.toJson(myObject2));

Converting json format using java bean

I have a json string something similar
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","geo_position":{"latitude":52.39886,"longitude":13.06566}},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","geo_position":{"latitude":44.66978,"longitude":-74.98131}}]}
I am trying to convert to
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","latitude":52.39886,"longitude":13.06566},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","latitude":44.66978,"longitude":-74.98131}]}
I am converting to java and again converting back using But I am gettin null in data
SourceJSON data=new Gson().fromJson(jsonArray, SourceJSON.class);
DestinationJSON destdata = new DestinationJSON();
destdata.setLatitide(data.getGeoLocation().getLatitide());
destdata.setLongitude(data.getGeoLocation().getLongitude());
destdata.setId(data.getId());
destdata.setType(data.getType());
destdata.setName(data.getName());
destdata.set_type(data.get_type());
Gson gson = new Gson();
String json = gson.toJson(destdata);
below are my beans
public class SourceJSON implements Serializable {
private List<GEOLocation> geoLocations;
private String _type;
private String id;
private String name;
private String type;
public String get_type() {
return _type;
}
public List<GEOLocation> getGeoLocations() {
return geoLocations;
}
public void setGeoLocations(List<GEOLocation> geoLocations) {
this.geoLocations = geoLocations;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
and
public class GEOLocation implements Serializable{
private String latitide;
private String longitude;
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
and destination java
public class DestinationJSON implements Serializable {
private String _type;
private String id;
private String name;
private String type;
private String latitide;
private String longitude;
public String get_type() {
return _type;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
All you need is this. You can try this class in your IDE with a simple copy&paste.
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20433539{
public static void main(String[] args){
String json = "{\"results\":"+
"[{\"_type\":\"Position\",\"_id\":377078,\"name\":\"Potsdam, Germany\",\"type\":\"location\",\"geo_position\":{\"latitude\":52.39886,\"longitude\":13.06566}},"+
"{\"_type\":\"Position\",\"_id\":410978,\"name\":\"Potsdam, USA\",\"type\":\"location\",\"geo_position\":{\"latitude\":44.66978,\"longitude\":-74.98131}}]}";
Gson gson = new Gson();
Map m = gson.fromJson(json, Map.class);
List<Map> innerList = (List<Map>) m.get("results");
for(Map result: innerList){
Map<String, Double> geo_position = (Map<String, Double>) result.get("geo_position");
result.put("latitude", geo_position.get("latitude"));
result.put("longitude", geo_position.get("longitude"));
result.remove("geo_position");
}
System.out.println(gson.toJson(m));
}
}
Of course, it works under the assumption that you always want to flat geo information.
Explanation: It's convenient to use POJO when working with Gson, but it's not the only way. Gson can also deseralize to Arrays/Maps if you do not specify the expected result. So I did, and then I manipulated the structure to unfold your data. After that, Gson can serialize Arrays/Maps structure again to your desidered JSON.

Json Object conversion to java object using jackson

I have following json data
{"id":10606,
"name":"ProgrammerTitle",
"objectMap":{"programme-title":"TestProgramme","working-title":"TestProgramme"}
}
I want to set this data to my pojo object
public class TestObject {
private Long id;
private String name;
#JsonProperty("programme-title")
private String programmeTitle;
#JsonProperty("working-title")
private String workingTitle;
}
Here i am able to set id and name in my test object but for object map i am not able to set data.
So i have made on more class for ObjectMap which contains programmeTitle & workingTitle this works fine but i can't set this fields directly to my pojo object
is this possible to set?
I am using Jackson Object Mapper to convert json data.
It is working fine if i create another java object inside my pojo like:
public class TestObject {
private Long id;
private String name;
#JsonProperty("objectMap")
private ObjectMap objectMap;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ObjectMap getObjectMap() {
return objectMap;
}
public void setObjectMap(ObjectMap objectMap) {
this.objectMap = objectMap;
}
}
public class ObjectMap {
#JsonProperty("programme-title")
private String programmeTitle;
#JsonProperty("working-title")
private String workingTitle;
public String getProgrammeTitle() {
return programmeTitle;
}
public void setProgrammeTitle(String programmeTitle) {
this.programmeTitle = programmeTitle;
}
public String getWorkingTitle() {
return workingTitle;
}
public void setWorkingTitle(String workingTitle) {
this.workingTitle = workingTitle;
}
}
If your JSON is like this
{"id":10606,
"name":"ProgrammerTitle",
"objectMap":{"programme-title":"TestProgramme","working-title":"TestProgramme"}
}
then you may write your object mapper class like this..
public class Program{
public static class ObjectMap{
private String programme_title, working_title;
public String getprogramme_title() { return programme_title; }
public String getworking_title() { return working_title; }
public void setprogramme_title(String s) { programme_title= s; }
public void setworking_title(String s) { working_title= s; }
}
private ObjectMap objMap;
private String name;
public ObjectMap getobjectMap () { return objMap; }
public void setObjectMap (ObjectMap n) { objMap= n; }
private Long id;
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
private String name;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
please refer this check it
You can write your own deserializer for this class:
class EntityJsonDeserializer extends JsonDeserializer<Entity> {
#Override
public Entity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Root root = jp.readValueAs(Root.class);
Entity entity = new Entity();
entity.setId(root.id);
entity.setName(root.name);
if (root.objectMap != null) {
entity.setProgrammeTitle(root.objectMap.programmeTitle);
entity.setWorkingTitle(root.objectMap.workingTitle);
}
return entity;
}
private static class Root {
public Long id;
public String name;
public Title objectMap;
}
private static class Title {
#JsonProperty("programme-title")
public String programmeTitle;
#JsonProperty("working-title")
public String workingTitle;
}
}
Your entity:
#JsonDeserialize(using = EntityJsonDeserializer.class)
class Entity {
private Long id;
private String name;
private String programmeTitle;
private String workingTitle;
//getters, setters, toString
}
And usage example:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Entity entity = mapper.readValue(jsonString, Entity.class);
System.out.println(entity);
}
}
Above program prints:
Entity [id=10606, name=ProgrammerTitle, programmeTitle=TestProgramme, workingTitle=TestProgramme]

SUPER CSV write bean to CSV

Here is my class,
public class FreebasePeopleResults {
public String intendedSearch;
public String weight;
public Double heightMeters;
public Integer age;
public String type;
public String parents;
public String profession;
public String alias;
public String children;
public String siblings;
public String spouse;
public String degree;
public String institution;
public String wikipediaId;
public String guid;
public String id;
public String gender;
public String name;
public String ethnicity;
public String articleText;
public String dob;
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Double getHeightMeters() {
return heightMeters;
}
public void setHeightMeters(Double heightMeters) {
this.heightMeters = heightMeters;
}
public String getParents() {
return parents;
}
public void setParents(String parents) {
this.parents = parents;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
public String getWikipediaId() {
return wikipediaId;
}
public void setWikipediaId(String wikipediaId) {
this.wikipediaId = wikipediaId;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEthnicity() {
return ethnicity;
}
public void setEthnicity(String ethnicity) {
this.ethnicity = ethnicity;
}
public String getArticleText() {
return articleText;
}
public void setArticleText(String articleText) {
this.articleText = articleText;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSiblings() {
return siblings;
}
public void setSiblings(String siblings) {
this.siblings = siblings;
}
public String getIntendedSearch() {
return intendedSearch;
}
public void setIntendedSearch(String intendedSearch) {
this.intendedSearch = intendedSearch;
}
}
Here is my CSV writer method
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
public class CSVUtils {
public static void writeCSVFromList(ArrayList<FreebasePeopleResults> people, boolean writeHeader) throws IOException{
//String[] header = new String []{"title","acronym","globalId","interfaceId","developer","description","publisher","genre","subGenre","platform","esrb","reviewScore","releaseDate","price","cheatArticleId"};
FileWriter file = new FileWriter("/brian/brian/Documents/people-freebase.csv", true);
// write the partial data
CsvBeanWriter writer = new CsvBeanWriter(file, CsvPreference.EXCEL_PREFERENCE);
for(FreebasePeopleResults person:people){
writer.write(person);
}
writer.close();
// show output
}
}
I keep getting output errors. Here is the error:
There is no content to write for line 2 context: Line: 2 Column: 0 Raw line:
null
Now, I know it is now totally null, so I am confused.
So it's been a while, and you've probably moved on from this, but...
The issue was actually that you weren't supplying the header to the write() method, i.e. it should be
writer.write(person, header);
Unfortunately the API is a little misleading in it's use of the var-args notation in the signature of the write() method, as it allows null to be passed in. The javadoc clearly states that you shouldn't do this, but there was no null-check in the implementation: hence the exception you were getting.
/**
* Write an object
*
* #param source
* at object (bean instance) whose values to extract
* #param nameMapping
* defines the fields of the class that must be written.
* null values are not allowed
* #since 1.0
*/
public void write(Object source, String... nameMapping) throws IOException,
SuperCSVReflectionException;
Super CSV 2.0.0-beta-1 is out now. It retains the var-args in the write() method, but fails fast if you provide a null, so you know exactly what's wrong when you get a NullPointerException with the following:
the nameMapping array can't be null as it's used to map from fields to
columns
It also includes many bug fixes and new features (including Maven support and a new Dozer extension for mapping nested properties and arrays/Collections).
I don't see where you create ArrayList<FreebasePeopleResults> people, but you might verify that it has more than one element. As an example of coding to the interface, consider using List<FreebasePeopleResults> people as the formal parameter.
Addendum: Have you been able to make this Code example: Write a file with a header work?
Example: Here's a simplified example. I think you just need to specify the nameMapping when you invoke write(). Those names determine what get methods to call via introspection.
Console output:
name,age
Alpha,1
Beta,2
Gamma,3
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
public class Main {
private static final List<Person> people = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
people.add(new Person("Alpha", 1));
people.add(new Person("Beta", 2));
people.add(new Person("Gamma", 3));
ICsvBeanWriter writer = new CsvBeanWriter(
new PrintWriter(System.out), CsvPreference.STANDARD_PREFERENCE);
try {
final String[] nameMapping = new String[]{"name", "age"};
writer.writeHeader(nameMapping);
for (Person p : people) {
writer.write(p, nameMapping);
}
} finally {
writer.close();
}
}
}
public class Person {
String name;
Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CellProcessor[] processors = new CellProcessor[] { new Optional(), new NotNull(),
new Optional(), new Optional(), new NotNull(), new Optional()};
CsvBeanWriter writer = new CsvBeanWriter(file, CsvPreference.EXCEL_PREFERENCE)
writer.write(data,properties,processors);

Categories