I want to create a custom dataFlavor with my class (Item.class)
#Override
public synchronized void drop(DropTargetDropEvent dtde) {
DataFlavor itemFlavor = new DataFlavor(Item.class, Item.class.getSimpleName());
try{
System.out.println(dtde.getTransferable().getTransferData(itemFlavor));
}catch(UnsupportedFlavorException | IOException e){
e.printStackTrace();
}
}
Item.class
public class Item {
private String classFile;
private String imgFile;
private String imgPath;
public Item(String classFile, String imgFile, String imgPath){
this.classFile = classFile;
this.imgFile = imgFile;
this.imgPath = imgPath;
}
public String getImgFile() {
return imgFile;
}
public void setImgFile(String imgFile) {
this.imgFile = imgFile;
}
public String getClassFile() {
return classFile;
}
public void setClassFile(String classFile) {
this.classFile = classFile;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
}
but I'm getting an error: java.awt.datatransfer.UnsupportedFlavorException: Item
Can you say what is wrong ?
I were using this docs https://docs.oracle.com/javase/tutorial/uiswing/dnd/dataflavor.html
Example, that demonstrate the problem DND Test Project
To get an error, try drag from JTable to JLayeredPane
Related
In the following file, i want to test the try method code block, using mockito. i want to test the mongo.java file using the j unit-mocking. SoaXMLLoggerRequestDTO is the model class file, and mongo.java is the class file having the method logRequestResponseXMLsWithTimeStamps.
mongo.java
public void logRequestResponseXMLsWithTimeStamps(final String requestType, final String requestXML,
final String responseXML, final long startTime, final long endTime, final long timeTaken,
final String status, final String userId, final String estimatetId) {
try {
SoaXMLLoggerRequestDTO loggerDTO = new SoaXMLLoggerRequestDTO();
loggerDTO.setRequestType(requestType);
loggerDTO.setRequestXml(requestXML);
loggerDTO.setResponseXml(responseXML);
loggerDTO.setCreatedBy(userId);
loggerDTO.setEstimateId(estimatetId + "");
loggerDTO.setStatus(status);
loggerDTO.setLatency(timeTaken);
LogExecutorService.writeToLog(new ESLoggerTask(loggerDTO, ESLoggerTask.IndexName.BNPSOALOG));
} catch (Exception e) {
LOGGER.error("Error in logRequestResponseXMLsWithTimeStamps : ", e);
throw new DAOException("Error logRequestResponseXMLs", e);
}
}
SoaXMLLoggerRequestDTO
public class SoaXMLLoggerRequestDTO extends LoggerRequestDTO{
private String requestType;
private String requestXml;
private String responseXml;
private Long latency;
private String status;
private String estimateId;
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getRequestXml() {
return requestXml;
}
public void setRequestXml(String requestXml) {
this.requestXml = requestXml;
}
public String getResponseXml() {
return responseXml;
}
public void setResponseXml(String responseXml) {
this.responseXml = responseXml;
}
public Long getLatency() {
return latency;
}
public void setLatency(Long latency) {
this.latency = latency;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEstimateId() {
return estimateId;
}
public void setEstimateId(String estimateId) {
this.estimateId = estimateId;
}
}
The following code will test the try block code.
public void test_logRequestResponseXMLsWithTimeStamps() {
estimateServicesMongoDao.logRequestResponseXMLsWithTimeStamps("ert", "rtr", "werffer",2L,0, 0, "drgfdf","sefw", null);
}
I'm trying to use New York Times API with Retrofit using Observable. But I'm getting this error when trying to use datas.
Can someone help me see where I'm wrong, please ?
Here is my ApiServices interface:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<TopStoryResult> getTopStories();
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.nytimes.com/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Here is my ApiStreams class
public static Observable<TopStoryResult> streamFetchTopStories(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getTopStories()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
public static Observable<List<NewsItem>> streamFetchNews(){
ApiServices mApiServices = ApiServices.retrofit.create(ApiServices.class);
return mApiServices.getResults()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.timeout(10, TimeUnit.SECONDS);
}
And this is what I'm trying to do in my MainActivity. For now I just want to display in a TextView the list of each Title...
//------------------------
// Update UI
//------------------------
private void updateUIWhenStartingHttpRequest() {
this.textView.setText("Downloading...");
}
private void updateUIWhenStopingHttpRequest(String response) {
this.textView.setText(response);
}
//------------------------
// Rx Java
//------------------------
private void executeRequestWithRetrofit(){
this.updateUIWhenStartingHttpRequest();
this.disposable = ApiStreams.streamFetchNews()
.subscribeWith(new DisposableObserver<List<NewsItem>>(){
#Override
public void onNext(List<NewsItem> topStories) {
Log.e("TAG", "On Next");
updateUIWithResult(topStories);
}
#Override
public void onError(Throwable e) {
Log.e("ERROR", Log.getStackTraceString(e));
}
#Override
public void onComplete() {
Log.e("TAG", "On Complete !");
}
});
}
private void updateUIWithResult(List<NewsItem> newsItemList){
StringBuilder mStringBuilder = new StringBuilder();
for (NewsItem news : newsItemList){
Log.e("TAG", "UPDATE UI" + news.getTitle());
mStringBuilder.append("- " + news.getTitle() + "\n");
}
updateUIWhenStopingHttpRequest(mStringBuilder.toString());
}
[EDIT]
There are my two models for TopStories and NewsItem
TopStories:
private String status;
private String copyright;
private String section;
private String lastUpdated;
private Integer numResults;
private List<NewsItem> results = null;
public String getStatus() {return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(String lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Integer getNumResults() {
return numResults;
}
public void setNumResults(Integer numResults) {
this.numResults = numResults;
}
public List<NewsItem> getResults() {
return results;
}
public void setResults(List<NewsItem> results) {
this.results = results;
}
NewsItem:
private String section;
private String subsection;
private String title;
private String url;
private String byline;
private String updated_date;
private String created_date;
private String published_date;
private String material_type_facet;
private String kicker;
#SerializedName("abstract")
private String abstract_string;
private List<Multimedia> multimedia;
private transient String des_facet;
private transient String org_facet;
private transient String per_facet;
private transient String geo_facet;
public NewsItem() {
}
public NewsItem(String url) {
this.url = url;
}
public NewsItem(String section, String subsection, String title, String url, String byline, String updated_date, String created_date, String published_date, String material_type_facet, String kicker) {
this.section = section;
this.subsection = subsection;
this.title = title;
this.url = url;
this.byline = byline;
this.updated_date = updated_date;
this.created_date = created_date;
this.published_date = published_date;
this.material_type_facet = material_type_facet;
this.kicker = kicker;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSubsection() {
return subsection;
}
public void setSubsection(String subsection) {
this.subsection = subsection;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getByline() {
return byline;
}
public void setByline(String byline) {
this.byline = byline;
}
public String getUpdated_date() {
return updated_date;
}
public void setUpdated_date(String updated_date) {
this.updated_date = updated_date;
}
public String getCreated_date() {
return created_date;
}
public void setCreated_date(String created_date) {
this.created_date = created_date;
}
public String getPublished_date() {
return published_date;
}
public void setPublished_date(String published_date) {
this.published_date = published_date;
}
public String getMaterial_type_facet() {
return material_type_facet;
}
public void setMaterial_type_facet(String material_type_facet) {
this.material_type_facet = material_type_facet;
}
public String getKicker() {
return kicker;
}
public void setKicker(String kicker) {
this.kicker = kicker;
}
public String getAbstract() {
return abstract_string;
}
public void setAbstract(String abstract_string) {
this.abstract_string = abstract_string;
}
public List<Multimedia> getMultimedia() {
return multimedia;
}
public void setMultimedia(List<Multimedia> multimedia) {
this.multimedia = multimedia;
}
public String getDes_facet() {
return des_facet;
}
public void setDes_facet(String des_facet) {
this.des_facet = des_facet;
}
public String getOrg_facet() {
return org_facet;
}
public void setOrg_facet(String org_facet) {
this.org_facet = org_facet;
}
public String getPer_facet() {
return per_facet;
}
public void setPer_facet(String per_facet) {
this.per_facet = per_facet;
}
public String getGeo_facet() {
return geo_facet;
}
public void setGeo_facet(String geo_facet) {
this.geo_facet = geo_facet;
}
Here is what the JSON looks like:
JSON
First when I tried this one with Github user API, it works fine. But I can't figure out where I'm wrong there...
Is anybody can help me please ?
Thanks a lot !
Expected BEGIN_ARRAY but was BEGIN_OBJECT
this means you are trying to a get a JSON Array as a List in JAVA but the api sent you a JSON OBJECT. So I cannot gather enough information but if I have to guess you should change this
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<List<NewsItem>> getResults();
to
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<NewsItemObject> getResults();
NewsItemObject is the Class that wraps NewsItem
In your ApiServices interface you expect that getResults() returns Observable<List<NewsItem>>. Based on JSON you getting back this is not gonna work, because your root JSON element is Object, not an Array.
You have to create new wrapper Class (ResultsWrapper) with "results" field type of List<NewsItem>. Your method in ApiServices interface will then be:
#GET("svc/topstories/v2/home.json?api-key=HiddenApiKeyJustForThisMessage")
Observable<ResultsWrapper> getResults();
That is what "Expected BEGIN_ARRAY but was BEGIN_OBJECT" says to you.
I'm struggling to implement a solution to retrieve multiple values from my api response ( https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=13060 ) and assign specific values to an array. Specifically values, strIngredient1, strIngredient2, strIngredient3 etc...
At present i created a POJO cocktail class as follows:
public class Cocktail implements Serializable {
#SerializedName("idDrink")
#Expose
private String idDrink;
#SerializedName("strDrink")
#Expose
private String strDrink;
#SerializedName("strVideo")
#Expose
private Object strVideo;
#SerializedName("strCategory")
#Expose
private String strCategory;
#SerializedName("strIBA")
#Expose
private Object strIBA;
#SerializedName("strAlcoholic")
#Expose
private String strAlcoholic;
#SerializedName("strGlass")
#Expose
private String strGlass;
#SerializedName("strInstructions")
#Expose
private String strInstructions;
#SerializedName("strDrinkThumb")
#Expose
private String strDrinkThumb;
#SerializedName("strIngredient1")
#Expose
private String strIngredient1;
#SerializedName("strIngredient2")
#Expose
private String strIngredient2;
#SerializedName("strIngredient3")
#Expose
private String strIngredient3;
#SerializedName("strIngredient4")
#Expose
private String strIngredient4;
#SerializedName("strIngredient5")
#Expose
private String strIngredient5;
#SerializedName("strIngredient6")
#Expose
private String strIngredient6;
#SerializedName("strIngredient7")
#Expose
private String strIngredient7;
#SerializedName("strIngredient8")
#Expose
private String strIngredient8;
#SerializedName("strIngredient9")
#Expose
private String strIngredient9;
#SerializedName("strIngredient10")
#Expose
private String strIngredient10;
#SerializedName("strIngredient11")
#Expose
private String strIngredient11;
#SerializedName("strIngredient12")
#Expose
private String strIngredient12;
#SerializedName("strIngredient13")
#Expose
private String strIngredient13;
#SerializedName("strIngredient14")
#Expose
private String strIngredient14;
#SerializedName("strIngredient15")
#Expose
private String strIngredient15;
#SerializedName("strMeasure1")
#Expose
private String strMeasure1;
#SerializedName("strMeasure2")
#Expose
private String strMeasure2;
#SerializedName("strMeasure3")
#Expose
private String strMeasure3;
#SerializedName("strMeasure4")
#Expose
private String strMeasure4;
#SerializedName("strMeasure5")
#Expose
private String strMeasure5;
#SerializedName("strMeasure6")
#Expose
private String strMeasure6;
#SerializedName("strMeasure7")
#Expose
private String strMeasure7;
#SerializedName("strMeasure8")
#Expose
private String strMeasure8;
#SerializedName("strMeasure9")
#Expose
private String strMeasure9;
#SerializedName("strMeasure10")
#Expose
private String strMeasure10;
#SerializedName("strMeasure11")
#Expose
private String strMeasure11;
#SerializedName("strMeasure12")
#Expose
private String strMeasure12;
#SerializedName("strMeasure13")
#Expose
private String strMeasure13;
#SerializedName("strMeasure14")
#Expose
private String strMeasure14;
#SerializedName("strMeasure15")
#Expose
private String strMeasure15;
#SerializedName("dateModified")
#Expose
private String dateModified;
public String getIdDrink() {
return idDrink;
}
public void setIdDrink(String idDrink) {
this.idDrink = idDrink;
}
public String getStrDrink() {
return strDrink;
}
public void setStrDrink(String strDrink) {
this.strDrink = strDrink;
}
public Object getStrVideo() {
return strVideo;
}
public void setStrVideo(Object strVideo) {
this.strVideo = strVideo;
}
public String getStrCategory() {
return strCategory;
}
public void setStrCategory(String strCategory) {
this.strCategory = strCategory;
}
public Object getStrIBA() {
return strIBA;
}
public void setStrIBA(Object strIBA) {
this.strIBA = strIBA;
}
public String getStrAlcoholic() {
return strAlcoholic;
}
public void setStrAlcoholic(String strAlcoholic) {
this.strAlcoholic = strAlcoholic;
}
public String getStrGlass() {
return strGlass;
}
public void setStrGlass(String strGlass) {
this.strGlass = strGlass;
}
public String getStrInstructions() {
return strInstructions;
}
public void setStrInstructions(String strInstructions) {
this.strInstructions = strInstructions;
}
public String getStrDrinkThumb() {
return strDrinkThumb;
}
public void setStrDrinkThumb(String strDrinkThumb) {
this.strDrinkThumb = strDrinkThumb;
}
public String getStrIngredient1() {
return strIngredient1;
}
public void setStrIngredient1(String strIngredient1) {
this.strIngredient1 = strIngredient1;
}
public String getStrIngredient2() {
return strIngredient2;
}
public void setStrIngredient2(String strIngredient2) {
this.strIngredient2 = strIngredient2;
}
public String getStrIngredient3() {
return strIngredient3;
}
public void setStrIngredient3(String strIngredient3) {
this.strIngredient3 = strIngredient3;
}
public String getStrIngredient4() {
return strIngredient4;
}
public void setStrIngredient4(String strIngredient4) {
this.strIngredient4 = strIngredient4;
}
public String getStrIngredient5() {
return strIngredient5;
}
public void setStrIngredient5(String strIngredient5) {
this.strIngredient5 = strIngredient5;
}
public String getStrIngredient6() {
return strIngredient6;
}
public void setStrIngredient6(String strIngredient6) {
this.strIngredient6 = strIngredient6;
}
public String getStrIngredient7() {
return strIngredient7;
}
public void setStrIngredient7(String strIngredient7) {
this.strIngredient7 = strIngredient7;
}
public String getStrIngredient8() {
return strIngredient8;
}
public void setStrIngredient8(String strIngredient8) {
this.strIngredient8 = strIngredient8;
}
public String getStrIngredient9() {
return strIngredient9;
}
public void setStrIngredient9(String strIngredient9) {
this.strIngredient9 = strIngredient9;
}
public String getStrIngredient10() {
return strIngredient10;
}
public void setStrIngredient10(String strIngredient10) {
this.strIngredient10 = strIngredient10;
}
public String getStrIngredient11() {
return strIngredient11;
}
public void setStrIngredient11(String strIngredient11) {
this.strIngredient11 = strIngredient11;
}
public String getStrIngredient12() {
return strIngredient12;
}
public void setStrIngredient12(String strIngredient12) {
this.strIngredient12 = strIngredient12;
}
public String getStrIngredient13() {
return strIngredient13;
}
public void setStrIngredient13(String strIngredient13) {
this.strIngredient13 = strIngredient13;
}
public String getStrIngredient14() {
return strIngredient14;
}
public void setStrIngredient14(String strIngredient14) {
this.strIngredient14 = strIngredient14;
}
public String getStrIngredient15() {
return strIngredient15;
}
public void setStrIngredient15(String strIngredient15) {
this.strIngredient15 = strIngredient15;
}
public String getStrMeasure1() {
return strMeasure1;
}
public void setStrMeasure1(String strMeasure1) {
this.strMeasure1 = strMeasure1;
}
public String getStrMeasure2() {
return strMeasure2;
}
public void setStrMeasure2(String strMeasure2) {
this.strMeasure2 = strMeasure2;
}
public String getStrMeasure3() {
return strMeasure3;
}
public void setStrMeasure3(String strMeasure3) {
this.strMeasure3 = strMeasure3;
}
public String getStrMeasure4() {
return strMeasure4;
}
public void setStrMeasure4(String strMeasure4) {
this.strMeasure4 = strMeasure4;
}
public String getStrMeasure5() {
return strMeasure5;
}
public void setStrMeasure5(String strMeasure5) {
this.strMeasure5 = strMeasure5;
}
public String getStrMeasure6() {
return strMeasure6;
}
public void setStrMeasure6(String strMeasure6) {
this.strMeasure6 = strMeasure6;
}
public String getStrMeasure7() {
return strMeasure7;
}
public void setStrMeasure7(String strMeasure7) {
this.strMeasure7 = strMeasure7;
}
public String getStrMeasure8() {
return strMeasure8;
}
public void setStrMeasure8(String strMeasure8) {
this.strMeasure8 = strMeasure8;
}
public String getStrMeasure9() {
return strMeasure9;
}
public void setStrMeasure9(String strMeasure9) {
this.strMeasure9 = strMeasure9;
}
public String getStrMeasure10() {
return strMeasure10;
}
public void setStrMeasure10(String strMeasure10) {
this.strMeasure10 = strMeasure10;
}
public String getStrMeasure11() {
return strMeasure11;
}
public void setStrMeasure11(String strMeasure11) {
this.strMeasure11 = strMeasure11;
}
public String getStrMeasure12() {
return strMeasure12;
}
public void setStrMeasure12(String strMeasure12) {
this.strMeasure12 = strMeasure12;
}
public String getStrMeasure13() {
return strMeasure13;
}
public void setStrMeasure13(String strMeasure13) {
this.strMeasure13 = strMeasure13;
}
public String getStrMeasure14() {
return strMeasure14;
}
public void setStrMeasure14(String strMeasure14) {
this.strMeasure14 = strMeasure14;
}
public String getStrMeasure15() {
return strMeasure15;
}
public void setStrMeasure15(String strMeasure15) {
this.strMeasure15 = strMeasure15;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
And my API call is as follows:
#Override
protected Cocktail doInBackground(Cocktail... cocktails) {
Call<Cocktails> call = mApiService.getCocktail(id);
try {
Response<Cocktails> response = call.execute();
this.cocktails = response.body();
this.cocktail = this.cocktails.getCocktail().get(0);
Log.i(TAG, "Success: " + response.body().toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e);
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException: " + e);
e.printStackTrace();
}
return cocktail;
}
I know enough to realise that a large number of variables, ingredients and measures (many of which are empty) is the wrong approach but i'm struggling to find a solution with retrofit to create an array of these values. I've not found any way to assign multiple SerializedNames to a single array variable?
The option that jumps out at me is looping through the response pulling out the key values in onSuccess but this seems to go against the simplicity of using retrofit?
I'm trying to store a coordnates (array of double) using Realm-java,but I'm not able to do it.
Here is an example of json that I'm trying to parse:
{"_id":"597cd98b3af0b6315576d717",
"comarca":"string",
"font":null,
"imatge":"string",
"location":{
"coordinates":[41.64642,1.1393],
"type":"Point"
},
"marca":"string",
"municipi":"string",
"publisher":"string",
"recursurl":"string",
"tematica":"string",
"titol":"string"
}
My global object code is like that
public class Images extends RealmObject implements Serializable {
#PrimaryKey
private String _id;
private String recursurl;
private String titol;
private String municipi;
private String comarca;
private String marca;
private String imatge;
#Nullable
private Location location;
private String tematica;
private String font;
private String parentRoute;
public Location getLocation() {return location;}
public void setLocation(Location location) {this.location = location;}
public String getParentRoute() {
return parentRoute;
}
public void setParentRoute(String parentRoute) {
this.parentRoute = parentRoute;
}
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public String getRecursurl() {
return recursurl;
}
public void setRecursurl(String recursurl) {
this.recursurl = recursurl;
}
public String getTitol() {
return titol;
}
public void setTitol(String titol) {
this.titol = titol;
}
public String getMunicipi() {
return municipi;
}
public void setMunicipi(String municipi) {
this.municipi = municipi;
}
public String getComarca() {
return comarca;
}
public void setComarca(String comarca) {
this.comarca = comarca;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getImatge() {
return imatge;
}
public void setImatge(String imatge) {
this.imatge = imatge;
}
public String getTematica() {
return tematica;
}
public void setTematica(String tematica) {
this.tematica = tematica;
}
And Location is a composite of type and a realmlist
Location.java
public class Location extends RealmObject implements Serializable {
private String type;
private RealmList<RealmDoubleObject> coordinates;
public Location() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RealmList<RealmDoubleObject> getCoordinates() {
return coordinates;
}
public void setCoordinates(RealmList<RealmDoubleObject> coordinates) {
this.coordinates = coordinates;
}
}
RealmDoubleObject.java
public class RealmDoubleObject extends RealmObject implements Serializable{
private Double value;
public RealmDoubleObject() {
}
public Double getDoublevalue() {
return value;
}
public void setDoublevalue(Double value) {
this.value = value;
}
}
The error is com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at path $[0].location.coordinates[0] but I'm not able to figure out why this number is not "fitting" by RealmDoubleObject.
For those that not familiar with realm RealmList doesn't work and you have to build your own realm object.
Thank you. I hope to find some Realm experts here!
SOLVED:
using Gson deserializer it can be done
First we have to initialize the gson object like this
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
#Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.registerTypeAdapter(new TypeToken<RealmList<RealmDoubleObject>>() {}.getType(), new TypeAdapter<RealmList<RealmDoubleObject>>() {
#Override
public void write(JsonWriter out, RealmList<RealmDoubleObject> value) throws IOException {
// Ignore
}
#Override
public RealmList<RealmDoubleObject> read(JsonReader in) throws IOException {
RealmList<RealmDoubleObject> list = new RealmList<RealmDoubleObject>();
in.beginArray();
while (in.hasNext()) {
Double valor = in.nextDouble();
list.add(new RealmDoubleObject(valor));
}
in.endArray();
return list;
}
})
.create();
And then we have to put some other constructor method
public RealmDoubleObject(double v) {
this.value = v;
}
and this is all.
Thanks for the help #EpicPandaForce
I want to unmarshall the following xml into another a parent object as defined below. But it always returns NULL.
Incoming XML:
<contentFiles>
<contentFile>
<contentFileName>cwb_reg_content_IB20C0F504A9A11E281E4C8BF76F4977C.pdf</contentFileName>
<title><![CDATA[SEC No-Action Guidance Expanding the Definition of “Ready Market” for Certain Foreign Equity Securities]]></title>
<sourcePublicationDate>20121219</sourcePublicationDate>
<alternateDocNumbers>
<alternateDocNumber>12345-b</alternateDocNumber>
</alternateDocNumbers>
<citesAffected>
<cite>SEA Rule 15c3-1</cite>
</citesAffected>
</contentFile>
</contentFiles>
Parent class corresponding to <contentFiles>
#XmlRootElement(name = "contentFiles")
public class RtSuperQuickMetadata
{
private List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems;
public RtSuperQuickMetadata()
{
rtSuperQuickMetadataItems = new ArrayList<RtSuperQuickMetadataItem>();
}
public List<RtSuperQuickMetadataItem> getRtSuperQuickMetadataItems()
{
return rtSuperQuickMetadataItems;
}
public void setRtSuperQuickMetadataItems(
List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems)
{
this.rtSuperQuickMetadataItems = rtSuperQuickMetadataItems;
}
}
Parent class corresponding to <contentFile>
#XmlRootElement(name = "contentFile")
public class RtSuperQuickMetadataItem
{
private String contentFileName;
private String title;
private String sourcePublicationDate;
private List<AlternateDocNumber> alternateDocNumbers;
private List<Cite> citesAffected;
public RtSuperQuickMetadataItem()
{
alternateDocNumbers = new ArrayList<AlternateDocNumber>();
citesAffected = new ArrayList<Cite>();
}
public List<AlternateDocNumber> getAlternateDocNumbers()
{
return alternateDocNumbers;
}
public List<Cite> getCitesAffected()
{
return citesAffected;
}
public String getContentFileName()
{
return contentFileName;
}
public String getSourcePublicationDate()
{
return sourcePublicationDate;
}
public String getTitle()
{
return title;
}
public void setAlternateDocNumbers(List<AlternateDocNumber> alternateDocNumbers)
{
this.alternateDocNumbers = alternateDocNumbers;
}
public void setCitesAffected(List<Cite> citesAffected)
{
this.citesAffected = citesAffected;
}
public void setContentFileName(String contentFileName)
{
this.contentFileName = contentFileName;
}
public void setSourcePublicationDate(String sourcePublicationDate)
{
this.sourcePublicationDate = sourcePublicationDate;
}
public void setTitle(String title)
{
this.title = title;
}
}
#XmlRootElement(name = "alternateDocNumber")
class AlternateDocNumber
{
private String alternateDocNumber;
public String getAlternateDocNumber()
{
return alternateDocNumber;
}
public void setAlternateDocNumber(String alternateDocNumber)
{
this.alternateDocNumber = alternateDocNumber;
}
#Override
public String toString()
{
return "AlternateDocNumber [alternateDocNumber=" + alternateDocNumber + "]";
}
}
#XmlRootElement(name = "cite")
class Cite
{
private String cite;
public String getCite()
{
return cite;
}
public void setCite(String cite)
{
this.cite = cite;
}
#Override
public String toString()
{
return "Cite [cite=" + cite + "]";
}
}
Unmarshaller code using JAXB:
public RtSuperQuickMetadata unmarshallXml(final File metadataFile)
throws JAXBException, FileNotFoundException
{
RtSuperQuickMetadata rtSuperQuickMetadata = null;
try
{
JAXBContext jc = JAXBContext.newInstance(RtSuperQuickMetadata.class);
Unmarshaller um = jc.createUnmarshaller();
rtSuperQuickMetadata =
(RtSuperQuickMetadata) um.unmarshal(metadataFile);
}
catch (JAXBException e)
{
String msg = "Malformed XML supplied as Metadata" + " Msg " + e.getMessage();
LOG.error(msg, e);
throw new RuntimeException(msg, e);
}
return rtSuperQuickMetadata;
}
You have too many XmlRootElements, you generally want to use this with the top element only. What you want to do is label the children as XmlElement.
Remove the XmlRootElement annotation from all but your root element (i.e. RtSuperQuickMetadata), and label them with XmlElement in the class from which they will be loaded.
So, as an example, here is how your RtSuperQuickMetadata class should look:
#XmlRootElement(name = "contentFiles")
class RtSuperQuickMetadata
{
private List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems;
public RtSuperQuickMetadata()
{
rtSuperQuickMetadataItems = new ArrayList<RtSuperQuickMetadataItem>();
}
#XmlElement(name = "contentFile")
public List<RtSuperQuickMetadataItem> getRtSuperQuickMetadataItems()
{
return rtSuperQuickMetadataItems;
}
public void setRtSuperQuickMetadataItems(
List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems)
{
this.rtSuperQuickMetadataItems = rtSuperQuickMetadataItems;
}
}
Transfer this principle to alternateDocNumbers and citesAffected as well.
If you want to see an example of how the Unmarshaller thinks your XML is formatted based off your annotations, you can create your structure in code and use the Marshaller. Here is a quick and ugly example:
RtSuperQuickMetadata rtSuperQuickMetadata = new RtSuperQuickMetadata();
List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems = new ArrayList<RtSuperQuickMetadataItem>();
rtSuperQuickMetadata.setRtSuperQuickMetadataItems(rtSuperQuickMetadataItems);
RtSuperQuickMetadataItem item = new RtSuperQuickMetadataItem();
rtSuperQuickMetadataItems.add(item);
ArrayList<Cite> cites = new ArrayList<Cite>();
Cite cite = new Cite();
cite.setCiteStr("MyCite");
cites.add(cite);
item.setCitesAffected(cites);
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(rtSuperQuickMetadata, System.out);
This will output the result to System.out. You can put this in a file instead, whatever suits your needs.
I have added this answer to address the follow up questions you posted as comments on the answer given by cklab.
I had another question. Why doesn't jaxb automatically allocate memory
for the lists contained in the object. Why do we need to assign memory
in a constructor for it ?
You do not need to, see below.
While unmarshalling these items the following isn't being saved into
the metadata object. 12 I
need to add another element for this to be generated ??
See mapping below.
RtSuperQuickMetadata
import java.util.*;
import javax.xml.bind.annotation.*;
#XmlRootElement(name = "contentFiles")
public class RtSuperQuickMetadata {
private List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems;
#XmlElement(name="contentFile")
public List<RtSuperQuickMetadataItem> getRtSuperQuickMetadataItems() {
return rtSuperQuickMetadataItems;
}
public void setRtSuperQuickMetadataItems(
List<RtSuperQuickMetadataItem> rtSuperQuickMetadataItems) {
this.rtSuperQuickMetadataItems = rtSuperQuickMetadataItems;
}
}
RtSuperQuickMetadataItem
import java.util.List;
import javax.xml.bind.annotation.XmlType;
#XmlType(propOrder={"contentFileName", "title", "sourcePublicationDate", "alternateDocNumbers", "citesAffected"})
public class RtSuperQuickMetadataItem {
private String contentFileName;
private String title;
private String sourcePublicationDate;
private List<AlternateDocNumber> alternateDocNumbers;
private List<Cite> citesAffected;
public List<AlternateDocNumber> getAlternateDocNumbers() {
return alternateDocNumbers;
}
public List<Cite> getCitesAffected() {
return citesAffected;
}
public String getContentFileName() {
return contentFileName;
}
public String getSourcePublicationDate() {
return sourcePublicationDate;
}
public String getTitle() {
return title;
}
public void setAlternateDocNumbers(
List<AlternateDocNumber> alternateDocNumbers) {
this.alternateDocNumbers = alternateDocNumbers;
}
public void setCitesAffected(List<Cite> citesAffected) {
this.citesAffected = citesAffected;
}
public void setContentFileName(String contentFileName) {
this.contentFileName = contentFileName;
}
public void setSourcePublicationDate(String sourcePublicationDate) {
this.sourcePublicationDate = sourcePublicationDate;
}
public void setTitle(String title) {
this.title = title;
}
}
AlternateDocNumber
class AlternateDocNumber {
private String alternateDocNumber;
public String getAlternateDocNumber() {
return alternateDocNumber;
}
public void setAlternateDocNumber(String alternateDocNumber) {
this.alternateDocNumber = alternateDocNumber;
}
}
Cite
class Cite {
private String cite;
public String getCite() {
return cite;
}
public void setCite(String cite) {
this.cite = cite;
}
}