How do I get an item from POJO classes in Android? - java

I am trying to get a specific Item from an API in my android application.
Here is the JSON response of the api:
{
"response": {
"items": [
{
"episode_id": 9599548,
"type": "RECORDED",
"title": "Adabule muferad 100916",
"duration": 3165940,
"explicit": false,
"show_id": 1392538,
"author_id": 7725967,
"site_url": "https://www.spreaker.com/episode/9599548",
"image_url": "https://d1bm3dmew779uf.cloudfront.net/large/f390b915e356de35055d971be5110dcb.jpg",
"image_original_url": "https://d3wo5wojvuv7l.cloudfront.net/images.spreaker.com/original/f390b915e356de35055d971be5110dcb.jpg",
"published_at": "2016-10-09 11:01:48",
"download_enabled": true,
"waveform_url": "https://d3770qakewhkht.cloudfront.net/episode_9599548.gz.json?v=qB6pQ6"
}
],
"next_url": "https://api.spreaker.com/v2/users/7725967/episodes?filter=listenable&last_id=9599548&limit=1"
}
}
I have three Java classes Items, Response and RadioProgramInfo.
Here are their codes respectively:
Items.java
public class Items
{
public String duration;
public String title;
public String download_enabled;
public String image_original_url;
public String image_url;
public String explicit;
public String episode_id;
public String author_id;
public String show_id;
public String type;
public String waveform_url;
public String published_at;
public String site_url;
public String getDuration ()
{
return duration;
}
public void setDuration (String duration)
{
this.duration = duration;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getDownload_enabled ()
{
return download_enabled;
}
public void setDownload_enabled (String download_enabled)
{
this.download_enabled = download_enabled;
}
public String getImage_original_url ()
{
return image_original_url;
}
public void setImage_original_url (String image_original_url)
{
this.image_original_url = image_original_url;
}
public String getImage_url ()
{
return image_url;
}
public void setImage_url (String image_url)
{
this.image_url = image_url;
}
public String getExplicit ()
{
return explicit;
}
public void setExplicit (String explicit)
{
this.explicit = explicit;
}
public String getEpisode_id ()
{
return episode_id;
}
public void setEpisode_id (String episode_id)
{
this.episode_id = episode_id;
}
public String getAuthor_id ()
{
return author_id;
}
public void setAuthor_id (String author_id)
{
this.author_id = author_id;
}
public String getShow_id ()
{
return show_id;
}
public void setShow_id (String show_id)
{
this.show_id = show_id;
}
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
public String getWaveform_url ()
{
return waveform_url;
}
public void setWaveform_url (String waveform_url)
{
this.waveform_url = waveform_url;
}
public String getPublished_at ()
{
return published_at;
}
public void setPublished_at (String published_at)
{
this.published_at = published_at;
}
public String getSite_url ()
{
return site_url;
}
public void setSite_url (String site_url)
{
this.site_url = site_url;
}
#Override
public String toString()
{
return "ClassPojo [duration = "+duration+", title = "+title+", download_enabled = "+download_enabled+", image_original_url = "+image_original_url+", image_url = "+image_url+", explicit = "+explicit+", episode_id = "+episode_id+", author_id = "+author_id+", show_id = "+show_id+", type = "+type+", waveform_url = "+waveform_url+", published_at = "+published_at+", site_url = "+site_url+"]";
}
}
Response.java
public class Response
{
private Items[] items;
private String next_url;
public Items[] getItems ()
{
return items;
}
public void setItems (Items[] items)
{
this.items = items;
}
public String getNext_url ()
{
return next_url;
}
public void setNext_url (String next_url)
{
this.next_url = next_url;
}
#Override
public String toString()
{
return "ClassPojo [items = "+items+", next_url = "+next_url+"]";
}
}
RadioProgramInfo.java
public class RadioProgramInfo
{
private Response response;
public Response getResponse ()
{
return response;
}
public void setResponse (Response response)
{
this.response = response;
}
#Override
public String toString()
{
return "ClassPojo [response = "+response+"]";
}
}
I am trying to access a specific Item called "site_url" which is located in Items.java
The code in my main class to try to access site_url is this:
Items url2 = new Items();
String streamURL = String.valueOf(url2)+"/shoutcast?force_http=true";
// new HttpRequestTask().execute();
// return true;
String url = "http://api.spreaker.com/listen/episode/9451446/shoutcast?force_http=true";
//String url2 = Items.class.getName(site_url);
public MainActivity() {
}
//System.out.println(streamURL);
public class HttpRequestTask extends AsyncTask<Void, Void, Items> {
protected Items doInBackground(Void... params) {
try {
final String url = String.valueOf(streamURL);
RestTemplate restTemplate = new RestTemplate();
//restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Items streamlink = restTemplate.getForObject(url, Items.class);
return streamlink;
}
catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return url2;
}
}
When I run my program (a media player app):
It tells me that the url is null in value (I debug mode on the program as it executes).
How do I correctly access the item in the JSON response I am after?
I am really stuck on this one.
---UPDATE-----
Here is the response from the console:
10-09 15:25:39.522 2586-2647/software.blackstone.com.salafimasjidradioseries E/MainActivity: 'messageConverters' must not be empty
java.lang.IllegalArgumentException: 'messageConverters' must not be empty
at org.springframework.util.Assert.notEmpty(Assert.java:269)
at org.springframework.web.client.HttpMessageConverterExtractor.<init>(HttpMessageConverterExtractor.java:53)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:235)
at software.blackstone.com.salafimasjidradioseries.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:46)
at software.blackstone.com.salafimasjidradioseries.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
.... and the complete MainActivity Code is this:
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
static MediaPlayer mPlayer;
ImageButton buttonPlay;
ImageButton buttonStop;
Items url2 = new Items();
String streamURL = String.valueOf(url2)+"/shoutcast?force_http=true";
// new HttpRequestTask().execute();
// return true;
String url = "http://api.spreaker.com/listen/episode/9451446/shoutcast?force_http=true";
//String url2 = Items.class.getName(site_url);
public MainActivity() {
}
//System.out.println(streamURL);
public class HttpRequestTask extends AsyncTask<Void, Void, Items> {
protected Items doInBackground(Void... params) {
try {
final String url = String.valueOf(streamURL);
RestTemplate restTemplate = new RestTemplate();
//restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Items streamlink = restTemplate.getForObject(url, Items.class);
return streamlink;
}
catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}
return url2;
}
}
#Override
protected void onStart() {
super.onStart();
new HttpRequestTask().execute();
}

i admittedly don't have any experience using Spring libraries for mobile development. there are, however, several other popular libraries at your disposal that are typically used to accomplish your goal.
below is an example i whipped using your DTO classes. i added these dependencies via my app's build.gradle:
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.google.code.gson:gson:2.4'
OkHttp is a library for creating + executing HTTP requests
Gson is a library for (un)marshaling data as json
the code should be pretty self-explanatory. i've just plugged in the bits to do my HTTP GET and marshal the data into the DTO within the AsyncTask.
public class MainActivity extends AppCompatActivity {
private MediaPlayer mPlayer = new MediaPlayer();
private OkHttpClient client = new OkHttpClient();
private Gson gson = new Gson();
public class HttpRequestTask extends AsyncTask<Void,Void,Items[]> {
protected Items[] doInBackground(Void... params) {
final Request request = new Request.Builder()
.url("https://api.myjson.com/bins/1z98u")
.build();
Items[] items = null;
try {
final com.squareup.okhttp.Response response = client.newCall(request).execute();
if(response.isSuccessful()) {
final RadioProgramInfo radioProgramInfo = gson.fromJson(response.body().charStream(), RadioProgramInfo.class);
items = radioProgramInfo.getResponse().getItems();
} else {
throw new RuntimeException("ooops!");
}
} catch (Throwable t) {
Log.e("MainActivity", t.getMessage(), t);
}
return items;
}
#Override
protected void onPostExecute(Items[] items) {
try {
mPlayer.setDataSource(items[0].getSite_url());
mPlayer.prepareAsync();
} catch(IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
new HttpRequestTask().execute();
}
}
hope that helps!

Since youre not really sure what to use and are currently using Spring, I'd recommend you to take a look at Retrofit which does exactly what you are looking for. It has very good documentation and a lot of examples of exactly what you're trying to do.. Here's a pretty good introduction to it: square.github.io/retrofit

Related

How to solve E/error: End of input at line 1 column 1 path $ in android studio

When I try to call rest API in the android studio I get an error that:
E/error: End of input at line 1 column 1 path $
I use firebase for the database and retrofit2 library.
But when I call the values a go to the firebase database and call the onFailure in call.enqueue() method.
public class APis {
public static final String URL = "http://192.168.178.43:8081/api/";
public static userService setuser() {
return client.getClient(URL).create(userService.class);
}
}
public interface userService {
#Headers("Content-Type: application/json")
#POST("signup")
Call<userlog> adduser(#Body userlog userlog);
}
public class userlog {
#SerializedName("email")
#Expose
private String emial_;
#SerializedName("password")
#Expose
private String password_;
#SerializedName("name")
#Expose
private String name_;
public userlog() {
}
public userlog(String emial_, String password, String name_) {
this.emial_ = emial_;
this.password_ = password;
this.name_ = name_;
}
public String getEmial_() {
return emial_;
}
public void setEmial_(String emial_) {
this.emial_ = emial_;
}
public String getPassword_() {
return password_;
}
public void setPassword_(String password_) {
this.password_ = password_;
}
public String getName_() {
return name_;
}
public void setName_(String name_) {
this.name_ = name_;
}
}
public void setPassword_(String password_) {
this.password_ = password_;
}
}
private void adduser_(userlog userll) {
service = APis.setuser();
Call<userlog> call = service.adduser(userll);
call.enqueue(new Callback<userlog>() {
#Override
public void onResponse(Call<userlog> call, Response<userlog> response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
/* userdetails.setUserid(firebaseAuth.getUid());
userdetails.setEmail_(emailId.getText().toString());
startActivity(new Intent(SignupActivity.this, MainnewActivity.class));*/
}
}
#Override
public void onFailure(Call<userlog> call, Throwable t) {
Log.e("error", t.getMessage());
Toast.makeText(getApplicationContext(), "not Successdd", Toast.LENGTH_SHORT).show();
}
});
}
when I call "adduser_(userll)" method, I get a notification that "not Successdd".
The problem related to retrofit, i think the problem because the response of the call come as null or empty
you can create NullConverterFactory.class :
public class NullConverterFactory extends Converter.Factory {
#Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
return new Converter<ResponseBody, Object>() {
#Override
public Object convert(ResponseBody body) throws IOException {
if (body.contentLength() == 0) return null;
return delegate.convert(body);
}
};
}
}
and add to the create of the retrofit
baseUrl(Config.URL+"/")
.client(okHttpClient)
// -----add here-------
.addConverterFactory(new NullConverterFactory())
//---------------------
.addConverterFactory(GsonConverterFactory.create())
.build()

Retrofit Get Data Object

I have a data like this, and i want get report and criteria data.
{
"response_code": 200,
"message": "Your report data has been loaded.",
"data": {
"report": [
{
"id_report": 1,
"report_name": "report name A"
},
{
"id_report": 2,
"report_name": "report name B"
}
],
"criteria": [
{
"id_criteria": 1,
"criteria_name": "criteria name A"
},
{
"id_criteria": 2,
"criteria_name": "criteria name B"
}
]
}
}
And i get data in java using retrofit. And this is my java class.
GetReport.java
#SerializedName("response_code")
private int response_code;
#SerializedName("status")
private boolean status;
#SerializedName("message")
private String message;
#SerializedName("data")
Call<Data> listData;
Data.java
#SerializedName("report")
private List<Report> reportList;
#SerializedName("criteria")
private List<Criteria> criteriaList;
And this how i call the data.
public void populateData() {
Call<GetReport> getReportCall = apiInterface.getReportCall();
getReportCall.enqueue(new Callback<GetReport>() {
#Override
public void onResponse(Call<GetReport> call, Response<GetReport> response) {
response.body().getListData().enqueue(new Callback<Data>() {
#Override
public void onResponse(Call<Data> call, Response<Data> response) {
List<Report> reportList = response.body().getReportList();
Log.d("TAGGGGGGGGGG", String.valueOf(reportList.size()));
}
#Override
public void onFailure(Call<Data> call, Throwable t) {
t.printStackTrace();
}
});
}
#Override
public void onFailure(Call<GetReport> call, Throwable t) {
t.printStackTrace();
}
});
}
When I run the program, my activity closes immediately. When I look at logcat, there is too much running log data so I can't see where the error is.
I have managed to attempt and solve your problem with the following code. I copied and pasted the JSON you provided above at JSONbin.io so that I can be able to call it using an API call. I did not modify the structure of the JSON at all.
App build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
GetReport.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class GetReport {
#SerializedName("response_code")
int response_code;
#SerializedName("message")
String message;
#SerializedName("data")
Data data;
public int getResponse_code() {
return response_code;
}
public void setResponse_code(int response_code) {
this.response_code = response_code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}}
Data.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Data {
#SerializedName("report")
List<Report> reportList;
#SerializedName("criteria")
List<Criteria> criteriaList;
public List<Report> getReportList() {
return reportList;
}
public void setReportList(List<Report> reportList) {
this.reportList = reportList;
}
public List<Criteria> getCriteriaList() {
return criteriaList;
}
public void setCriteriaList(List<Criteria> criteriaList) {
this.criteriaList = criteriaList;
}}
Criteria.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Criteria {
#SerializedName("id_criteria")
int id_criteria;
#SerializedName("criteria_name")
String criteria_name;
public Criteria(int id_criteria, String criteria_name) {
this.id_criteria = id_criteria;
this.criteria_name = criteria_name;
}
public int getId_criteria() {
return id_criteria;
}
public void setId_criteria(int id_criteria) {
this.id_criteria = id_criteria;
}
public String getCriteria_name() {
return criteria_name;
}
public void setCriteria_name(String criteria_name) {
this.criteria_name = criteria_name;
}}
Report.java
package com.example.retrofitapp;
import com.google.gson.annotations.SerializedName;
public class Report {
#SerializedName("id_report")
int id_report;
#SerializedName("report_name")
String report_name;
public Report(int id_report, String report_name) {
this.id_report = id_report;
this.report_name = report_name;
}
public int getId_report() {
return id_report;
}
public void setId_report(int id_report) {
this.id_report = id_report;
}
public String getReport_name() {
return report_name;
}
public void setReport_name(String report_name) {
this.report_name = report_name;
}}
RetrofitClient.java
package com.example.retrofitapp.api;
import com.google.gson.*;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
public static Retrofit retrofit;
public static Retrofit getRetrofitClient(String baseUrl){
if(retrofit==null){
Gson gson = new GsonBuilder().setLenient().create();
retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create(gson)).build();
}
return retrofit;
}}
Constants.java
package com.example.retrofitapp;
public class Constants {
public static String base_url = "https://api.jsonbin.io/";
}
Api.java
package com.example.retrofitapp.api;
import com.example.retrofitapp.GetReport;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
public interface Api {
#Headers("Secret-key:$2a$10$WxkkTylkdR7NwGSoPwrfy.Odxtj7MR2vDtYZBp9cOd0SaYGVRmhOm")
#GET("/b/5ff8172e63e86571a2e35639")
Call<GetReport> getReport();
}
MainActivity.java
package com.example.retrofitapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.retrofitapp.api.Api;
import com.example.retrofitapp.api.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call method here
populateData();
}
private void populateData() {
Retrofit retrofit = RetrofitClient.getRetrofitClient(Constants.base_url);
Api api = retrofit.create(Api.class);
Call<GetReport> getReportCall = api.getReport();
//make asynchronous request
getReportCall.enqueue(new Callback<GetReport>() {
#Override
public void onResponse(Call<GetReport> call, Response<GetReport> response) {
if(response.code() == 200){
GetReport getReport = (GetReport) response.body();
//get response code
int responseCode = getReport.getResponse_code();
//get message
String message = getReport.getMessage();
//get data
Data data = getReport.getData();
//get reports(loop)
for(Report report : data.getReportList()){
//your report here
}
//get criteria(loop)
for(Criteria criteria : data.getCriteriaList()){
//your criteria here
}
}
}
#Override
public void onFailure(Call<GetReport> call, Throwable t) {
//do something if the request failed
}
});
}}
That is how I solved it.

On reload of page, mvp4g history mechanism fails

I have implemented a history mechanism for my mvp4g project. When I traverse through the pages, I can see the url also getting changed. But on reload of any page other than home page, always home page gets displayed instead of the desired page?
This is my implementation:
#History(type = HistoryConverterType.SIMPLE)
public class CustomHistoryConverter implements HistoryConverter<AppEventBus> {
private CustomEventBus eventBus;
#Override
public void convertFromToken(String historyName, String param, CustomEventBus eventBus) {
this.eventBus = eventBus;
eventBus.dispatch(historyName, param);
}
public String convertToToken(String eventName, String name) {
return name;
}
public String convertToToken(String eventName) {
return eventName;
}
public String convertToToken(String eventName, String name, String type) {
return name;
}
public boolean isCrawlable() {
return false;
}
}
and event bus related code :
#Events(startPresenter=PageOnePresenter.class,historyOnStart=true)
public interface CustomEventBus extends EventBusWithLookup {
#Start
#Event(handlers = PageOnePresenter.class)
void start();
#InitHistory
#Event(handlers = PageOnePresenter.class)
void init();
#Event(handlers = PageTwoPresenter.class, name = "page2", historyConverter = CustomHistoryConverter.class)
void getPageTwo();
#Event(handlers = PageThreePresenter.class, name = "page3", historyConverter=CustomHistoryConverter.class)
void getPageThree();
#Event(handlers=PageOnePresenter.class, name = "page1", historyConverter=CustomHistoryConverter.class)
void getPageOne();
#Event(handlers=PageOnePresenter.class)
void setPageTwo(HistoryPageTwoView view);
#Event(handlers=PageOnePresenter.class)
void setPageThree(HistoryPageThreeView view);
}
The HistoryConverter needs to be improved.
In fact, that the event has no parameter, you should return an empty string. Update the HistoryConverter that it looks like that:
#History(type = HistoryConverterType.SIMPLE)
public class CustomHistoryConverter implements HistoryConverter<AppEventBus> {
private CustomEventBus eventBus;
#Override
public void convertFromToken(String historyName, String param, CustomEventBus eventBus) {
this.eventBus = eventBus;
// TODO handle the param in cases where you have more than one parameter
eventBus.dispatch(historyName, param);
}
public String convertToToken(String eventName, String name) {
return name;
}
public String convertToToken(String eventName) {
return "";
}
public String convertToToken(String eventName, String name, String type) {
return name - "-!-" type;
}
public boolean isCrawlable() {
return false;
}
}
Hope that helps.

MusixMatch API and GSON: Using track.snippet.get instead of track.lyrics.get

I am working on the final project for an intro to Java class. Part of the project involves getting a lyric snippet from MusixMatch using their API. I am able to get lyrics from the API using track.lyrics.get, but cannot get snippets using tracks.snippet.get.
I started with a Java wrapper found here: https://github.com/sachin-handiekar/jMusixMatch and added my own classes to get a snippet based on the track.snippet.get API method.
When I run the program I get this error:
java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at
line 1 column 102 path $.message.body
My getSnippet method and applicable classes follow. They are based on the getLyrics method and classes found in the original wrapper.
public Snippet getSnippet(int trackID) throws MusixMatchException {
Snippet snippet = null;
SnippetGetMessage message = null;
Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.API_KEY, apiKey);
params.put(Constants.TRACK_ID, new String("" + trackID));
String response = null;
response = MusixMatchRequest.sendRequest(Helper.getURLString(
Methods.TRACK_SNIPPET_GET, params));
Gson gson = new Gson();
try {
message = gson.fromJson(response, SnippetGetMessage.class);
} catch (JsonParseException jpe) {
handleErrorResponse(response);
}
snippet = message.getContainer().getBody().getSnippet();
return snippet;
}
The Snippet Class
package org.jmusixmatch.entity.snippet;
import com.google.gson.annotations.SerializedName;
/**
* Created by kyledhebert on 4/30/15.
* Objects of this clas represent a lyric snippet from the
* MusixMatch API.
*/
public class Snippet {
#SerializedName("snippet_language")
private int snippetLanguage;
#SerializedName("restricted")
private int restricted;
#SerializedName("instrumental")
private int instrumental;
#SerializedName("snippet_body")
private String snippetBody;
#SerializedName("script_tracking_url")
private String scriptTrackingURL;
#SerializedName("pixel_tracking_url")
private String pixelTrackingURL;
#SerializedName("html_tracking_url")
private String htmlTrackingURL;
#SerializedName("updated_time")
private String updatedTime;
public int getSnippetLanguage() {
return snippetLanguage;
}
public void setSnippetLanguage(int snippetLanguage) {
this.snippetLanguage = snippetLanguage;
}
public int getRestricted() {
return restricted;
}
public void setRestricted(int restricted) {
this.restricted = restricted;
}
public int getInstrumental() {
return instrumental;
}
public void setInstrumental(int instrumental) {
this.instrumental = instrumental;
}
public String getSnippetBody() {
return snippetBody;
}
public void setSnippetBody(String snippetBody) {
this.snippetBody = snippetBody;
}
public String getPixelTrackingURL() {
return pixelTrackingURL;
}
public void setPixelTrackingURL(String pixelTrackingURL) {
this.pixelTrackingURL = pixelTrackingURL;
}
public String getScriptTrackingURL() {
return scriptTrackingURL;
}
public void setScriptTrackingURL(String scriptTrackingURL) {
this.scriptTrackingURL = scriptTrackingURL;
}
public String getHtmlTrackingURL() {
return htmlTrackingURL;
}
public void setHtmlTrackingURL(String htmlTrackingURL) {
this.htmlTrackingURL = htmlTrackingURL;
}
public String getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(String updatedTime) {
this.updatedTime = updatedTime;
}
}
The SnippetGetBody class:
package org.jmusixmatch.entity.snippet.get;
import com.google.gson.annotations.SerializedName;
import org.jmusixmatch.entity.snippet.Snippet;
public class SnippetGetBody {
#SerializedName("snippet")
private Snippet snippet;
public Snippet getSnippet() {
return snippet;
}
public void setSnippet(Snippet snippet) {
this.snippet = snippet;
}
}
The SnippetGetContainer class:
package org.jmusixmatch.entity.snippet.get;
import com.google.gson.annotations.SerializedName;
import org.jmusixmatch.entity.Header;
public class SnippetGetContainer {
#SerializedName("body")
private SnippetGetBody body;
#SerializedName("header")
private Header header;
public SnippetGetBody getBody() {
return body;
}
public void setBody(SnippetGetBody body) {
this.body = body;
}
public Header getHeader() {
return header;
}
public void setHeader(Header header) {
this.header = header;
}
}
The SnippetGetMessage class:
package org.jmusixmatch.entity.lyrics.get;
import com.google.gson.annotations.SerializedName;
public class SnippetGetMessage {
#SerializedName("message")
private SnippetGetContainer container;
public void setContainer(SnippetGetContainer container) {
this.container = container;
}
public SnippetGetContainer getContainer() {
return container;
}
}
I was not able to reproduce your exact error message, but I did find the following error: snippet_language is a String, not an int. Change the type (and associated getters and setters) to:
#SerializedName("snippet_language")
private String snippetLanguage;
I used the sample Json response from here to make this work. If these two changes don't fix your problem, please edit your question with the actual Json response that is making your program not work.

java- error when i am trying to convert xml response into pojo using xstream

I am getting an error for the following code in a java web app--
XStream xstream = new XStream();
apiresponse myClassObject;
myClassObject= xstream.fromXML(resp);
The error is shown for the line of code just above this line--
error="Type mismatch- cannot convert from Object to apiresponse"
Given below is the XML that I have to parse---
<apiresponse version="1" xmlns="http://ahrefs.com/schemas/api/links/1">
<resultset_links count="2">
<result>
<source_url>http://ahrefs.com/robot/</source_url>
<destination_url>http://blog.ahrefs.com/</destination_url>
<source_ip>50.22.24.236</source_ip>
<source_title>Ahrefs – backlinks research tool</source_title>
<visited>2011-08-31T07:56:53Z</visited>
<anchor>Blog</anchor>
<rating>257.674000</rating>
<link_type>text</link_type>
<is_nofollow>false</is_nofollow>
</result>
<result>
<source_url>http://apps.vc/</source_url>
<destination_url>http://ahrefs.com/robot/</destination_url>
<source_ip>64.20.55.86</source_ip>
<source_title>Device info</source_title>
<visited>2011-08-27T18:59:31Z</visited>
<anchor>http://ahrefs.com/robot/</anchor>
<rating>209.787100</rating>
<link_type>text</link_type>
<is_nofollow>false</is_nofollow>
</result>
</resultset_links>
</apiresponse>
I have created the following java classes to obtain data from above xml---
package com.arvindikchari.linkdatasmith.domain;
final public class apiresponse {
protected resultset_links rlinks;
public apiresponse() {
}
public resultset_links getRlinks()
{
return rlinks;
}
public setRlinks(resultset_links rlinks)
{
this.rlinks=rlinks;
}
}
final public class resultset_links {
protected List<result> indiv_result = new ArrayList<result>();
public resultset_links() {
}
public List<result> getIndiv_result()
{
return List;
}
public void setIndiv_result(List<result> indiv_result)
{
this.indiv_result=indiv_result;
}
}
final public class result {
protected String source_url;
protected String destination_url;
protected String source_ip;
protected String source_title;
protected String visited;
protected String anchor;
protected String rating;
protected String link_type;
public result() {
}
public String getSource_url()
{
return source_url;
}
public void setSource_url(String source_url)
{
this.source_url=source_url;
}
public String getDestination_url()
{
return destination_url;
}
public void setDestination_url(String destination_url)
{
this.destination_url=destination_url;
}
public String getSource_ip()
{
return source_ip;
}
public void setSource_ip(String source_ip)
{
this.source_ip=source_ip;
}
public String getSource_title()
{
return source_title;
}
public void setSource_title(String source_title)
{
this.source_title=source_title;
}
public String getVisited()
{
return visited;
}
public void setVisited(String visited)
{
this.visited=visited;
}
public String getAnchor()
{
return anchor;
}
public void setAnchor(String anchor)
{
this.anchor=anchor;
}
public String getRating()
{
return rating;
}
public void setRating(String rating)
{
this.rating=rating;
}
public String getLink_type()
{
return link_type;
}
public void setLink_type(String link_type)
{
this.link_type=link_type;
}
}
What am I doing wrong here?
You have many errors, but the one corresponding to your message is you have to cast the result of xstream.fromXML to an apiresponse' object :
apiresponse result = (apiresponse)xstream.fromXML(resp);
Moreover, the code you provided (the Java classes) do not compile, there are many errors.
Here are some improvements :
Result.java :
#XStreamAlias("result")
public class Result {
protected String source_url;
protected String destination_url;
protected String source_ip;
protected String source_title;
protected String visited;
protected String anchor;
protected String rating;
protected String link_type;
protected Boolean is_nofollow;
public Result() {
}
public String getSource_url()
{
return source_url;
}
public void setSource_url(String source_url)
{
this.source_url=source_url;
}
public String getDestination_url()
{
return destination_url;
}
public void setDestination_url(String destination_url)
{
this.destination_url=destination_url;
}
public String getSource_ip()
{
return source_ip;
}
public void setSource_ip(String source_ip)
{
this.source_ip=source_ip;
}
public String getSource_title()
{
return source_title;
}
public void setSource_title(String source_title)
{
this.source_title=source_title;
}
public String getVisited()
{
return visited;
}
public void setVisited(String visited)
{
this.visited=visited;
}
public String getAnchor()
{
return anchor;
}
public void setAnchor(String anchor)
{
this.anchor=anchor;
}
public String getRating()
{
return rating;
}
public void setRating(String rating)
{
this.rating=rating;
}
public String getLink_type()
{
return link_type;
}
public void setLink_type(String link_type)
{
this.link_type=link_type;
}
public Boolean getIs_nofollow() {
return is_nofollow;
}
public void setIs_nofollow(Boolean is_nofollow) {
this.is_nofollow = is_nofollow;
}
ResultsetLinks.java :
#XStreamAlias("resultset_links")
public class ResultsetLinks {
#XStreamImplicit(itemFieldName="result")
protected List<Result> indivResult = new ArrayList<Result>();
public ResultsetLinks() {
}
public List<Result> getResult()
{
return indivResult;
}
public void setResult(List<Result> indiv_result)
{
this.indivResult =indiv_result;
}
}
ApiResponse.java :
#XStreamAlias("apiresponse")
public class ApiResponse {
#XStreamAlias("resultset_links")
protected ResultsetLinks rlinks;
public ApiResponse() {
}
public ResultsetLinks getRlinks()
{
return rlinks;
}
public void setRlinks(ResultsetLinks rlinks)
{
this.rlinks=rlinks;
}
}
And finally your code to unmarshall the XML :
XStream xstream = new XStream();
xstream.processAnnotations(ApiResponse.class);
xstream.processAnnotations(ResultsetLinks.class);
xstream.processAnnotations(Result.class);
ApiResponse result = (ApiResponse)xstream.fromXML(resp);
All this code is working fine with Xstream 1.4.2
Try to follow Sun's coding convention for your classes name, attributes names, etc...
Use XstreamAliases to adapt the Java class name to the XML name.

Categories

Resources