I have the below pojo which I'm trying to serialize and deserialize using spring support for jackson processor,Below is my POJO class
public class Contract {
String term;
private List<Payment> paymentList=new ArrayList<Payment>();
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public List<Payment> getPaymentList() {
return paymentList;
}
public void setPaymentList(List<Payment> paymentList) {
this.paymentList = paymentList;
}
}
In the above class if there is a list,I am getting null pointer exception when I am using JUnit test cases mentioned below:
package com.budco.vsc.jsonmapping;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.samples.mvc.ajax.account.Contract;
import org.springframework.samples.mvc.ajax.json.ConversionServiceAwareObjectMapper;
import org.springframework.util.Assert;
public class ContractJsonBindingTests{
Logger log = LoggerFactory.getLogger(ContractJsonBindingTests.class);
private MappingJacksonHttpMessageConverter converter;
private ObjectMapper objectMapper;
private String testPayload = "{\"term\":\"krish\"}";
#Before
public void setUp() {
FormattingConversionServiceFactoryBean factoryBean = new FormattingConversionServiceFactoryBean();
factoryBean.afterPropertiesSet();
ConversionService conversionService = factoryBean.getObject();
objectMapper = new ConversionServiceAwareObjectMapper(conversionService);
converter = new MappingJacksonHttpMessageConverter();
converter.setObjectMapper(objectMapper);
}
#Test
#SuppressWarnings("unchecked")
public void testAnnotationDrivenJsonConversion() throws Exception {
MockHttpInputMessage inputMessage = new MockHttpInputMessage(testPayload.getBytes("UTF-8"));
MediaType jsonType = new MediaType("application", "json");
inputMessage.getHeaders().setContentType(jsonType);
Contract contract = (Contract) converter.read((Class) Contract.class, inputMessage);
Assert.notNull(contract);
log.debug(contract.toString());
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(contract, jsonType, outputMessage);
log.debug(outputMessage.getBody().toString());
assertEquals("Incoming and outgoing JSON representations expected to match", testPayload, outputMessage.getBody().toString());
}
private static class MockHttpInputMessage implements HttpInputMessage {
private final HttpHeaders headers = new HttpHeaders();
private final InputStream body;
public MockHttpInputMessage(byte[] contents) {
Assert.notNull(contents, "'contents' must not be null");
this.body = new ByteArrayInputStream(contents);
}
public HttpHeaders getHeaders() {
return headers;
}
public InputStream getBody() throws IOException {
return body;
}
}
public class MockHttpOutputMessage implements HttpOutputMessage {
private final HttpHeaders headers = new HttpHeaders();
private final ByteArrayOutputStream body = new ByteArrayOutputStream();
public HttpHeaders getHeaders() {
return headers;
}
public OutputStream getBody() throws IOException {
return body;
}
public byte[] getBodyAsBytes() {
return body.toByteArray();
}
public String getBodyAsString(Charset charset) {
byte[] bytes = getBodyAsBytes();
return new String(bytes, charset);
}
}
}
The stack trace is
java.lang.NullPointerException
at org.springframework.samples.mvc.ajax.json.FormatAnnotationIntrospector.findDeserializer(FormatAnnotationIntrospector.java:33)
at org.codehaus.jackson.map.AnnotationIntrospector$Pair.findDeserializer(AnnotationIntrospector.java:1058)
at org.codehaus.jackson.map.deser.BasicDeserializerFactory.findDeserializerFromAnnotation(BasicDeserializerFactory.java:462)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.constructSettableProperty(BeanDeserializerFactory.java:606)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.addBeanProps(BeanDeserializerFactory.java:460)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:149)
at org.codehaus.jackson.map.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:116)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:342)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:264)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:244)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializer.findDeserializer(StdDeserializer.java:482)
at org.codehaus.jackson.map.deser.BeanDeserializer.resolve(BeanDeserializer.java:271)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._resolveDeserializer(StdDeserializerProvider.java:348)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:303)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:244)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.BasicDeserializerFactory.createCollectionDeserializer(BasicDeserializerFactory.java:182)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createDeserializer(StdDeserializerProvider.java:332)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:264)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:244)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializer.findDeserializer(StdDeserializer.java:482)
at org.codehaus.jackson.map.deser.BeanDeserializer.resolve(BeanDeserializer.java:271)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._resolveDeserializer(StdDeserializerProvider.java:348)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCache2(StdDeserializerProvider.java:303)
at org.codehaus.jackson.map.deser.StdDeserializerProvider._createAndCacheValueDeserializer(StdDeserializerProvider.java:244)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findValueDeserializer(StdDeserializerProvider.java:111)
at org.codehaus.jackson.map.deser.StdDeserializerProvider.findTypedValueDeserializer(StdDeserializerProvider.java:127)
at org.codehaus.jackson.map.ObjectMapper._findRootDeserializer(ObjectMapper.java:2046)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1980)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1331)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:124)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:153)
at com.budco.vsc.jsonmapping.ContractJsonBindingTests.testAnnotationDrivenJsonConversion(ContractJsonBindingTests.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Note:- If I'm removing the list property(paymentList) from the POJO then there is no problem. That means the above is not working when the POJO content some collection properties.If any body have any idea please help me.
EDIT:
The payment class
public class Payment {
private BigDecimal amount;
private String payType;
private String transactionType;
private String chargeOrCancelFlag;
private String type;
private String authCode;
private Date authRequestDate;
private String authStatus;
private String authTransactioncode;
private SystemUser systemUser;
private String mailOrEmailInvoice;
private String monthlyBillOnDay;
private CreditCard creditCard;
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public String getChargeOrCancelFlag() {
return chargeOrCancelFlag;
}
public void setChargeOrCancelFlag(String chargeOrCancelFlag) {
this.chargeOrCancelFlag = chargeOrCancelFlag;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public Date getAuthRequestDate() {
return authRequestDate;
}
public void setAuthRequestDate(Date authRequestDate) {
this.authRequestDate = authRequestDate;
}
public String getAuthStatus() {
return authStatus;
}
public void setAuthStatus(String authStatus) {
this.authStatus = authStatus;
}
public String getAuthTransactioncode() {
return authTransactioncode;
}
public void setAuthTransactioncode(String authTransactioncode) {
this.authTransactioncode = authTransactioncode;
}
public SystemUser getSystemUser() {
return systemUser;
}
public void setSystemUser(SystemUser systemUser) {
this.systemUser = systemUser;
}
public String getMailOrEmailInvoice() {
return mailOrEmailInvoice;
}
public void setMailOrEmailInvoice(String mailOrEmailInvoice) {
this.mailOrEmailInvoice = mailOrEmailInvoice;
}
public String getMonthlyBillOnDay() {
return monthlyBillOnDay;
}
public void setMonthlyBillOnDay(String monthlyBillOnDay) {
this.monthlyBillOnDay = monthlyBillOnDay;
}
public CreditCard getCreditCard() {
return creditCard;
}
public void setCreditCard(CreditCard creditCard) {
this.creditCard = creditCard;
}
}
The credit card class
public class CreditCard {
private String type;
private String cardNumber;
private String name;
private String securityCode;
private String expirationDate;
private String firstFourDigit;
private String secondFourDigit;
private String thirdFourDigit;
private String lastFourDigits;
private String zipCode;
public void setMonth(String month){
if(expirationDate==null)
expirationDate=month;
else
expirationDate=month+"/"+expirationDate;
}
public void setYear(String year){
if(expirationDate==null)
expirationDate=year;
else
expirationDate=expirationDate+"/"+year;
}
public String getMonth() {
return "";
}
public String getYear() {
return "";
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCardNumber() {
if (cardNumber == null)
cardNumber = firstFourDigit + secondFourDigit + thirdFourDigit
+ lastFourDigits;
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecurityCode() {
return securityCode;
}
public void setSecurityCode(String securityCode) {
this.securityCode = securityCode;
}
public String getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(String expirationDate) {
this.expirationDate = expirationDate;
}
public String getFirstFourDigit() {
return firstFourDigit;
}
public String getSecondFourDigit() {
return secondFourDigit;
}
public String getThirdFourDigit() {
return thirdFourDigit;
}
public String getLastFourDigits() {
return lastFourDigits;
}
public void setLastFourDigits(String lastFourDigits) {
this.lastFourDigits = lastFourDigits;
}
public void setFirstFourDigit(String firstFourDigit) {
this.firstFourDigit = firstFourDigit;
}
public void setSecondFourDigit(String secondFourDigit) {
this.secondFourDigit = secondFourDigit;
}
public void setThirdFourDigit(String thirdFourDigit) {
this.thirdFourDigit = thirdFourDigit;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
public void setMonth(String month){
// ...
}
public void setYear(String year){
// ...
}
Are the problem here. Because during introspection spring looks for a field with name being name of the setXXX, without set.
see FormatAnnotationIntrospector source code
EDIT (proposed solution):
public class CreditCard {
public static class ExpirationDate {
private String month;
private String year;
// getters, setter
#Override
public String toString() {
return month + "/" + year;
}
}
private String type;
private String cardNumber;
private String name;
private String securityCode;
private ExpirationDate expirationDate;
private String firstFourDigit;
private String secondFourDigit;
private String thirdFourDigit;
private String lastFourDigits;
private String zipCode;
public void setExpirationDate(ExpirationDate expDate){
this.expirationDate = expDate;
}
public ExpirationDate getExpirationDate(){
return this.expirationDate;
}
// other getters, setters
}
Related
I have a JSON object like the following:
...
{
"url": "checkout.bodenusa.com/en-US"
},
{
"url": [
".bonton.com/checkout/",
".bonton.com/CheckoutView"
]
}
...
How should my Java class look like for Response server.
I try this snippet, but it is incorrect:
#SerializedName("url")
#Expose
private List<String> urlList = null;
#SerializedName("url")
#Expose
private String url;
Create a model like
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Model {
#SerializedName("url")
#Expose
private List<String> url = null;
#SerializedName("apply")
#Expose
private Apply apply;
#SerializedName("controls")
#Expose
private Controls controls;
#SerializedName("remove")
#Expose
private Remove remove;
public List<String> getUrl() {
return url;
}
public void setUrl(List<String> url) {
this.url = url;
}
public Apply getApply() {
return apply;
}
public void setApply(Apply apply) {
this.apply = apply;
}
public Controls getControls() {
return controls;
}
public void setControls(Controls controls) {
this.controls = controls;
}
public Remove getRemove() {
return remove;
}
public void setRemove(Remove remove) {
this.remove = remove;
}
public class Controls {
#SerializedName("promo")
#Expose
private String promo;
#SerializedName("total")
#Expose
private String total;
#SerializedName("orderTotal")
#Expose
private String orderTotal;
#SerializedName("coupon")
#Expose
private String coupon;
public String getPromo() {
return promo;
}
public void setPromo(String promo) {
this.promo = promo;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getOrderTotal() {
return orderTotal;
}
public void setOrderTotal(String orderTotal) {
this.orderTotal = orderTotal;
}
public String getCoupon() {
return coupon;
}
public void setCoupon(String coupon) {
this.coupon = coupon;
}
}
public class Remove {
#SerializedName("type")
#Expose
private String type;
#SerializedName("submit")
#Expose
private String submit;
#SerializedName("timeout")
#Expose
private Integer timeout;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubmit() {
return submit;
}
public void setSubmit(String submit) {
this.submit = submit;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
public class Apply {
#SerializedName("type")
#Expose
private String type;
#SerializedName("submit")
#Expose
private String submit;
#SerializedName("timeout")
#Expose
private Integer timeout;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubmit() {
return submit;
}
public void setSubmit(String submit) {
this.submit = submit;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
}
Use this class along with a Custom TypeAdapter for Gson .Then it will work for both List and Object response .
ArrayAdapter class
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
public class ArrayAdapterFactory implements TypeAdapterFactory {
#Override
#SuppressWarnings({"unchecked", "rawtypes"})
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
TypeAdapter<T> typeAdapter = null;
try {
if (type.getRawType() == List.class || type.getRawType() == ArrayList.class) {
typeAdapter = new ArrayAdapter(gson,
(Class) ((ParameterizedType) type.getType())
.getActualTypeArguments()[0]);
}
} catch (Exception e) {
e.printStackTrace();
}
return typeAdapter;
}
}
ArrayAdapterFactory class
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class ArrayAdapter<T> extends TypeAdapter<List<T>> {
private Class<T> adapterclass;
private Gson gson;
public ArrayAdapter(Gson gson, Class<T> adapterclass) {
this.adapterclass = adapterclass;
this.gson = gson;
}
#Override
public List<T> read(JsonReader reader) throws IOException {
List<T> list = new ArrayList<T>();
final JsonToken token = reader.peek();
System.out.println(token);
// Handling of Scenario 2( Check JavaDoc for the class) :
if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
token == JsonToken.BOOLEAN) {
T inning = (T) gson.fromJson(reader, adapterclass);
list.add(inning);
} else if (token == JsonToken.BEGIN_OBJECT) {
// Handling of Scenario 1(Check JavaDoc for the class) :
T inning = (T) gson.fromJson(reader, adapterclass);
list.add(inning);
} else if (token == JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
#SuppressWarnings("unchecked")
T inning = (T) gson.fromJson(reader, adapterclass);
list.add(inning);
}
reader.endArray();
}
return list;
}
#Override
public void write(JsonWriter writer, List<T> value) throws IOException {
}
}
And register the adapter factory like this,
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
public class Example {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Use this link to generate POJO's
This question already has an answer here:
How to convert JSONArray to List with Gson?
(1 answer)
Closed 6 years ago.
How to convert a jsonArray with multiple jsonObjects to an arraylist using Gson.
Here is my Json String:
[{"AccommoAddress":{
"PostalCode":2109,
"Street":"22 Ararat Str",
"Town":"Westdene"
},
"AccommoDetails":{
"AccommoId":0,
"CleaningService":1,
"DSTV":1,
"DedicatedStudyArea":1
},
"AccommoID":1,
"AccommoMainImage":{
"CategoryId":0,
"ContentType":".png",
"DateUploaded":"2016-07-16",
"FileSize":2362,
"ImageCategory":"MAIN",
"ImageId":1,
"ImageName":"images.png"
}]
First , it's not a correct Json format.
"ImageName":"images.png" <- (you need to put a "}" here )
Second , create a entity
public class TargetEntity {
private AccommoAddressEntity AccommoAddress;
private AccommoDetailsEntity AccommoDetails;
private int AccommoID;
private AccommoMainImageEntity AccommoMainImage;
public AccommoAddressEntity getAccommoAddress() {
return AccommoAddress;
}
public void setAccommoAddress(AccommoAddressEntity AccommoAddress) {
this.AccommoAddress = AccommoAddress;
}
public AccommoDetailsEntity getAccommoDetails() {
return AccommoDetails;
}
public void setAccommoDetails(AccommoDetailsEntity AccommoDetails) {
this.AccommoDetails = AccommoDetails;
}
public int getAccommoID() {
return AccommoID;
}
public void setAccommoID(int AccommoID) {
this.AccommoID = AccommoID;
}
public AccommoMainImageEntity getAccommoMainImage() {
return AccommoMainImage;
}
public void setAccommoMainImage(AccommoMainImageEntity AccommoMainImage) {
this.AccommoMainImage = AccommoMainImage;
}
public static class AccommoAddressEntity {
private int PostalCode;
private String Street;
private String Town;
public int getPostalCode() {
return PostalCode;
}
public void setPostalCode(int PostalCode) {
this.PostalCode = PostalCode;
}
public String getStreet() {
return Street;
}
public void setStreet(String Street) {
this.Street = Street;
}
public String getTown() {
return Town;
}
public void setTown(String Town) {
this.Town = Town;
}
}
public static class AccommoDetailsEntity {
private int AccommoId;
private int CleaningService;
private int DSTV;
private int DedicatedStudyArea;
public int getAccommoId() {
return AccommoId;
}
public void setAccommoId(int AccommoId) {
this.AccommoId = AccommoId;
}
public int getCleaningService() {
return CleaningService;
}
public void setCleaningService(int CleaningService) {
this.CleaningService = CleaningService;
}
public int getDSTV() {
return DSTV;
}
public void setDSTV(int DSTV) {
this.DSTV = DSTV;
}
public int getDedicatedStudyArea() {
return DedicatedStudyArea;
}
public void setDedicatedStudyArea(int DedicatedStudyArea) {
this.DedicatedStudyArea = DedicatedStudyArea;
}
}
public static class AccommoMainImageEntity {
private int CategoryId;
private String ContentType;
private String DateUploaded;
private int FileSize;
private String ImageCategory;
private int ImageId;
private String ImageName;
public int getCategoryId() {
return CategoryId;
}
public void setCategoryId(int CategoryId) {
this.CategoryId = CategoryId;
}
public String getContentType() {
return ContentType;
}
public void setContentType(String ContentType) {
this.ContentType = ContentType;
}
public String getDateUploaded() {
return DateUploaded;
}
public void setDateUploaded(String DateUploaded) {
this.DateUploaded = DateUploaded;
}
public int getFileSize() {
return FileSize;
}
public void setFileSize(int FileSize) {
this.FileSize = FileSize;
}
public String getImageCategory() {
return ImageCategory;
}
public void setImageCategory(String ImageCategory) {
this.ImageCategory = ImageCategory;
}
public int getImageId() {
return ImageId;
}
public void setImageId(int ImageId) {
this.ImageId = ImageId;
}
public String getImageName() {
return ImageName;
}
public void setImageName(String ImageName) {
this.ImageName = ImageName;
}
}
}
Third
Gson gson = new Gson();
TargetEntity[] target = gson.fromJson(JsonString,TargetEntity[].class)
I'm using Kundera to do the persistence in MongoDB. I can persist some documents in my collection, but everytime that I try to find a specific document by id, I get this error
java.lang.ClassCastException: java.lang.String cannot be cast to com.mongodb.BasicDBList
com.impetus.kundera.persistence.AbstractEntityReader.findById(AbstractEntityReader.java:95)
com.impetus.client.mongodb.MongoEntityReader.findById(MongoEntityReader.java:72)
com.impetus.kundera.lifecycle.states.ManagedState.handleFind(ManagedState.java:com.impetus.kundera.graph.Node.find(Node.java:500)
com.impetus.kundera.persistence.PersistenceDelegator.find(PersistenceDelegator.java:225)
com.impetus.kundera.persistence.PersistenceDelegator.findById(PersistenceDelegator.java:174)
com.impetus.kundera.persistence.EntityManagerImpl.find(EntityManagerImpl.java:263)
My class definition is
package data.additional;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.google.common.collect.Lists;
#Entity
#Table(name = "reference", schema = "RcordsDB#pl_records")
public class Reference {
#Id
#Column(name="idReference")
private String idReference;
#Column(name="profile_id")
private String profile_id;
#Column(name="group_id")
private String group_id;
#Column(name="created")
private Date created;
#Column(name="last_modified")
private Date last_modified;
#Column(name="identifiers")
private List<String> identifiers = Lists.newArrayList();
#Column(name="abstractText")
private String abstractText;
#Column(name="tags")
private String tags;
#Column(name="type")
private String type;
#Column(name="source")
private String source;
#Column(name="title")
private String title;
#Column(name="title")
private List<String> authors = Lists.newArrayList();
#Column(name="year")
private Date year;
#Column(name="volume")
private String volume;
#Column(name="issue")
private String issue;
#Column(name="pages")
private String pages;
#Column(name="series")
private String series;
#Column(name="chapter")
private String chapter;
#Column(name="websites")
private String websites;
#Column(name="accesed")
private String accesed;
#Column(name="publisher")
private String publisher;
#Column(name="city")
private String city;
#Column(name="edition")
private String edition;
#Column(name="institution")
private String institution;
#Column(name="editors")
private List<String> editors = Lists.newArrayList();
#Column(name="keywords")
private List<String> keywords = Lists.newArrayList();
#Column(name="doi")
private String doi;
#Column(name="isbn")
private String isbn;
#Column(name="issn")
private String issn;
public String getIdReference() {
return idReference;
}
public void setIdReference(String idReference) {
this.idReference = idReference;
}
public String getProfile_id() {
return profile_id;
}
public void setProfile_id(String profile_id) {
this.profile_id = profile_id;
}
public String getGroup_id() {
return group_id;
}
public void setGroup_id(String group_id) {
this.group_id = group_id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLast_modified() {
return last_modified;
}
public void setLast_modified(Date last_modified) {
this.last_modified = last_modified;
}
public List<String> getIdentifiers() {
return identifiers;
}
public void setIdentifiers(List<String> identifiers) {
this.identifiers = identifiers;
}
public String getAbstractText() {
return abstractText;
}
public void setAbstractText(String abstractText) {
this.abstractText = abstractText;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public Date getYear() {
return year;
}
public void setYear(Date year) {
this.year = year;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getPages() {
return pages;
}
public void setPages(String pages) {
this.pages = pages;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public String getChapter() {
return chapter;
}
public void setChapter(String chapter) {
this.chapter = chapter;
}
public String getWebsites() {
return websites;
}
public void setWebsites(String websites) {
this.websites = websites;
}
public String getAccesed() {
return accesed;
}
public void setAccesed(String accesed) {
this.accesed = accesed;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
public List<String> getEditors() {
return editors;
}
public void setEditors(List<String> editors) {
this.editors = editors;
}
public List<String> getKeywords() {
return keywords;
}
public void setKeywords(List<String> keywords) {
this.keywords = keywords;
}
public String getDoi() {
return doi;
}
public void setDoi(String doi) {
this.doi = doi;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getIssn() {
return issn;
}
public void setIssn(String issn) {
this.issn = issn;
}
}
There is no error from Kundera side. The error is in the Entity class. You have given same Column Name to these two fields.
#Column(name="title")
private List<String> authors = Lists.newArrayList();
#Column(name="title")
private String title;
Update that name & your code will be working fine.
I am trying to read an XML file from java program. I am able to read its contents.I am posting the XML file from which i am reading contents.
<?xml version="1.0" encoding="UTF-8" ?>
<customer id="100">
<age>29</age>
<name>lucifer</name>
</customer>
i am able to write its contents through java program i am posting my code..
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
public class CheckClass {
public static void main(String[] args) {
try {
File file = new File("./file/NewFile.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer.age);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
But i have to read values from this XML file which i can not.This is my XML file
<?xml version="1.0" encoding="UTF-8"?>
<DBConfig ID="1" Name ="" DriverName="" HostName="localhost" PortName="" DBName="" ServiceName="" User="" PassWord="" sid="">
<TableConfig ID= "1" TableName="">
</TableConfig>
</DBConfig>
When i am trying to access this xml values through java class i am getting this error..
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "DBName"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getDBName()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.DBName
at com.gamma.DBConf
Class has two properties of the same name "sid"
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.getSid()
at com.gamma.DBConf
this problem is related to the following location:
at public java.lang.String com.gamma.DBConf.sid
at com.gamma.DBConf
at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.<init>(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(Unknown Source)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at com.gamma.ReadXML.main(ReadXML.java:22)
and this is my java classes
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DBConf {
public String Name;
public String DriverName;
public String HostName;
public String PortName;
public String DBName;
public String ServiceName;
public String User;
public String PassWord;
public String sid;
public String getName() {
return Name;
}
#XmlElement
public void setName(String name) {
Name = name;
}
public String getDriverName() {
return DriverName;
}
#XmlElement
public void setDriverName(String driverName) {
DriverName = driverName;
}
public String getHostName() {
return HostName;
}
#XmlElement
public void setHostName(String hostName) {
HostName = hostName;
}
public String getPortName() {
return PortName;
}
#XmlElement
public void setPortName(String portName) {
PortName = portName;
}
public String getDBName() {
return DBName;
}
#XmlElement
public void setDBName(String dBName) {
DBName = dBName;
}
public String getServiceName() {
return ServiceName;
}
#XmlElement
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getUser() {
return User;
}
#XmlElement
public void setUser(String user) {
User = user;
}
public String getPassWord() {
return PassWord;
}
#XmlElement
public void setPassWord(String passWord) {
PassWord = passWord;
}
public String getSid() {
return sid;
}
#XmlElement
public void setSid(String sid) {
this.sid = sid;
}
}
And this is the main class
public class ReadXML {
/**
* #param args
*/
public static void main(String[] args) {
try {
File file = new File("./file/dbconfig.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DBConf.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
DBConf db = (DBConf) jaxbUnmarshaller.unmarshal(file);
System.out.println(db.HostName);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
can anyone help
Note that you are annotating Attribute as Element. Fix that.
Even after that if problem occurs -
Try using - #XmlAccessorType(XmlAccessType.FIELD)
Move #XmlAttribute(name = "HostName") annotations to fields instead of accessor methods.
I am not sure if this is your problem. I faced a similar problem and this helped me. I wont guarantee that it will solve your problem but prima facie, it appears that above can fix it.
dbName, sid are Attributes, but you have annotated them #XmlElement. change all the attributes to #XmlAttribute.
Why don't you use
Xstream library
Example:
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
#XStreamAlias("Cat")
class Cat {
#XStreamAsAttribute
int age;
String name;
}
public class XStreamDemo {
public static void main(String[] args) {
XStream xstream = new XStream();
xstream.processAnnotations(Cat.class);
String xml = "<Cat age='4' ><name>Garfield</name></Cat>";
Cat cat = (Cat) xstream.fromXML(xml);
System.out.println("name -> " + cat.name);
System.out.println("age -> " + cat.age);
}
}
You need to add Xstream jar files in to classpath.
Use these classes.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"value"
})
#XmlRootElement(name = "TableConfig")
public class TableConfig {
#XmlValue
protected String value;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "TableName")
protected String tableName;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getTableName() {
return tableName;
}
public void setTableName(String value) {
this.tableName = value;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"tableConfig"
})
#XmlRootElement(name = "DBConfig")
public class DBConfig {
#XmlElement(name = "TableConfig", required = true)
protected TableConfig tableConfig;
#XmlAttribute(name = "ID")
protected Byte id;
#XmlAttribute(name = "Name")
protected String name;
#XmlAttribute(name = "DriverName")
protected String driverName;
#XmlAttribute(name = "HostName")
protected String hostName;
#XmlAttribute(name = "PortName")
protected String portName;
#XmlAttribute(name = "DBName")
protected String dbName;
#XmlAttribute(name = "ServiceName")
protected String serviceName;
#XmlAttribute(name = "User")
protected String user;
#XmlAttribute(name = "PassWord")
protected String passWord;
#XmlAttribute
protected String sid;
public TableConfig getTableConfig() {
return tableConfig;
}
public void setTableConfig(TableConfig value) {
this.tableConfig = value;
}
public Byte getID() {
return id;
}
public void setID(Byte value) {
this.id = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getDriverName() {
return driverName;
}
public void setDriverName(String value) {
this.driverName = value;
}
public String getHostName() {
return hostName;
}
public void setHostName(String value) {
this.hostName = value;
}
public String getPortName() {
return portName;
}
public void setPortName(String value) {
this.portName = value;
}
public String getDBName() {
return dbName;
}
public void setDBName(String value) {
this.dbName = value;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String value) {
this.serviceName = value;
}
public String getUser() {
return user;
}
public void setUser(String value) {
this.user = value;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String value) {
this.passWord = value;
}
public String getSid() {
return sid;
}
public void setSid(String value) {
this.sid = value;
}
}
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);