I am trying to parse the JSON array and add it to my adapter class.
My code:
String url = "https://api.github.com/users";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray(); // error in this line since there is no array name
for(int i = 0;i < results.length();i++){
JSONObject result = results.getJSONObject(i);
String name = result.getString("login");
users.add(new User(name.substring(0,1).toUpperCase() + name.substring(1),result.getString("avatar_url")));
}
// notify that data has changed in recyclerview
notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Log.e("cs50", "Json error", e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("cs50","Github User List error",error);
}
});
You can see that I'm trying to get a response from Github API URL but I'm getting error as there is no array name but my code requires a parameter. how can I parse it ?
Change this line
StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://api.github.com/users", response -> {
Log.d(TAG, "_ApiGetGithubUsers: " + response);
if (response != null && !response.isEmpty()) {
try {
JSONArray usersArray = new JSONArray(response);
for (int i = 0; i < usersArray.length(); i++) {
JSONObject user = usersArray.getJSONObject(i);
Log.d(TAG, "_ApiGetGithubUsers: "+user.getString("login"));
}
} catch (Exception e) {
Log.d(TAG, "_ApiGetGithubUsers: " + e);
Toast.makeText(context, R.string.someErrorOccurred, Toast.LENGTH_SHORT).show();
}
} else
Toast.makeText(context, R.string.someErrorOccurred, Toast.LENGTH_SHORT).show();
}, error -> {
});
AppController.getInstance().addToRequestQueue(stringRequest);
This is the method i used and it is working and parsing attaching the log image for reference.
I think you can use retrofit library, add the dependencies to app gradle.
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:retrofit:2.5'
Create User Class to get Response.
public class User {
#SerializedName("login")
#Expose
private String login;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("node_id")
#Expose
private String nodeId;
#SerializedName("avatar_url")
#Expose
private String avatarUrl;
#SerializedName("gravatar_id")
#Expose
private String gravatarId;
#SerializedName("url")
#Expose
private String url;
#SerializedName("html_url")
#Expose
private String htmlUrl;
#SerializedName("followers_url")
#Expose
private String followersUrl;
#SerializedName("following_url")
#Expose
private String followingUrl;
#SerializedName("gists_url")
#Expose
private String gistsUrl;
#SerializedName("starred_url")
#Expose
private String starredUrl;
#SerializedName("subscriptions_url")
#Expose
private String subscriptionsUrl;
#SerializedName("organizations_url")
#Expose
private String organizationsUrl;
#SerializedName("repos_url")
#Expose
private String reposUrl;
#SerializedName("events_url")
#Expose
private String eventsUrl;
#SerializedName("received_events_url")
#Expose
private String receivedEventsUrl;
#SerializedName("type")
#Expose
private String type;
#SerializedName("site_admin")
#Expose
private Boolean siteAdmin;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getGravatarId() {
return gravatarId;
}
public void setGravatarId(String gravatarId) {
this.gravatarId = gravatarId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHtmlUrl() {
return htmlUrl;
}
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
public String getFollowersUrl() {
return followersUrl;
}
public void setFollowersUrl(String followersUrl) {
this.followersUrl = followersUrl;
}
public String getFollowingUrl() {
return followingUrl;
}
public void setFollowingUrl(String followingUrl) {
this.followingUrl = followingUrl;
}
public String getGistsUrl() {
return gistsUrl;
}
public void setGistsUrl(String gistsUrl) {
this.gistsUrl = gistsUrl;
}
public String getStarredUrl() {
return starredUrl;
}
public void setStarredUrl(String starredUrl) {
this.starredUrl = starredUrl;
}
public String getSubscriptionsUrl() {
return subscriptionsUrl;
}
public void setSubscriptionsUrl(String subscriptionsUrl) {
this.subscriptionsUrl = subscriptionsUrl;
}
public String getOrganizationsUrl() {
return organizationsUrl;
}
public void setOrganizationsUrl(String organizationsUrl) {
this.organizationsUrl = organizationsUrl;
}
public String getReposUrl() {
return reposUrl;
}
public void setReposUrl(String reposUrl) {
this.reposUrl = reposUrl;
}
public String getEventsUrl() {
return eventsUrl;
}
public void setEventsUrl(String eventsUrl) {
this.eventsUrl = eventsUrl;
}
public String getReceivedEventsUrl() {
return receivedEventsUrl;
}
public void setReceivedEventsUrl(String receivedEventsUrl) {
this.receivedEventsUrl = receivedEventsUrl;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getSiteAdmin() {
return siteAdmin;
}
public void setSiteAdmin(Boolean siteAdmin) {
this.siteAdmin = siteAdmin;
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", id=" + id +
", nodeId='" + nodeId + '\'' +
", avatarUrl='" + avatarUrl + '\'' +
", gravatarId='" + gravatarId + '\'' +
", url='" + url + '\'' +
", htmlUrl='" + htmlUrl + '\'' +
", followersUrl='" + followersUrl + '\'' +
", followingUrl='" + followingUrl + '\'' +
", gistsUrl='" + gistsUrl + '\'' +
", starredUrl='" + starredUrl + '\'' +
", subscriptionsUrl='" + subscriptionsUrl + '\'' +
", organizationsUrl='" + organizationsUrl + '\'' +
", reposUrl='" + reposUrl + '\'' +
", eventsUrl='" + eventsUrl + '\'' +
", receivedEventsUrl='" + receivedEventsUrl + '\'' +
", type='" + type + '\'' +
", siteAdmin=" + siteAdmin +
'}';
}
}
Create a API interface for endpoint URL.
public interface APIInterface {
#GET("/users")
Call<List<User>> getGitHubUser();
}
Create Retrofit API Client.
public class APIClient {
/**
* Get Retrofit Instance
*/
private static Retrofit getRetrofitInstance() {
Gson gson = new GsonBuilder()
.setLenient()
.create();
return new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static APIInterface getApiInterface() {
return getRetrofitInstance().create(APIInterface.class);
}
}
Then Call the below method to get your parse data.
public void getUserList() {
APIInterface apiInterface=APIClient.getApiInterface();
Call<List<User>> call= apiInterface.getGitHubUser();
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
List<User> userList= response.body();
System.out.println(userList);
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
}
});
}
Related
In my Spring Controller I have:
List<User> Users = this.userService.UsersList();
mav = new ModelAndView("users");
mav.addObject("Users", Users);
When I iterate over Users I can see all the attributes values of every element of my list.
This is my .jsp code:
<c:forEach items="${Users}" var="usr">
${usr}
</c:forEach>
This is my users class:
#Entity
#Table(name="usuario")
public class User implements Serializable {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#JoinColumn(name = "id_perfil")
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Perfil perfil;
#Column(name="nombre")
private String nombre;
#Column(name="usuario")
private String usuario;
#Column(name="contrasenia")
private String contrasenia;
#Column(name="correo")
private String correo;
#Column(name="telefono")
private String telefono;
#Column(name="imagen_perfil")
private String imagen_perfil;
#Column(name="intento_fallido")
private int intento_fallido;
#Column(name="intranet_id")
private Integer intranet_id;
#Column(name="intranet_notaria")
private Integer intranet_notaria;
#Column(name="intranet_token_codigo")
private String intranet_token_codigo;
#Column(name="intranet_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date intranet_token_fecha;
#Column(name="tesoreria_token_codigo")
private String tesoreria_token_codigo;
#Column(name="tesoreria_token_fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date tesoreria_token_fecha;
#Column(name="activo")
private int activo;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Perfil getPerfil() { return perfil; }
public void setPerfil(Perfil perfil) { this.perfil = perfil; }
public String getNombre() { return nombre; }
public void setNombre(String nombre) { this.nombre = nombre; }
public String getUsuario() { return usuario; }
public void setUsuario(String usuario) { this.usuario = usuario; }
public String getContrasenia() { return contrasenia; }
public void setContrasenia(String contrasenia) { this.contrasenia = contrasenia; }
public String getCorreo() { return correo; }
public void setCorreo(String correo) { this.correo = correo; }
public String getTelefono() { return telefono; }
public void setTelefono(String telefono) { this.telefono = telefono; }
public String getImagenPerfil() { return imagen_perfil; }
public void setImagenPerfil(String imagen_perfil) { this.imagen_perfil = imagen_perfil; }
public int getIntentoFallido() { return intento_fallido; }
public void setIntentoFallido(int intento_fallido) { this.intento_fallido = intento_fallido; }
public Integer getIntranetId() { return intranet_id; }
public void setIntranetId(Integer intranet_id) { this.intranet_id = intranet_id; }
public Integer getIntranetNotaria() { return intranet_notaria; }
public void setIntranetNotaria(Integer intranet_notaria) { this.intranet_notaria = intranet_notaria; }
public String getIntranetTokenCodigo() { return intranet_token_codigo; }
public void setIntranetTokenCodigo(String intranet_token_codigo) { this.intranet_token_codigo = intranet_token_codigo; }
public Date getIntranetTokenFecha() { return intranet_token_fecha; }
public void setIntranetTokenFecha(Date intranet_token_fecha) { this.intranet_token_fecha = intranet_token_fecha; }
public String getTesoreriaTokenCodigo() { return tesoreria_token_codigo; }
public void setTesoreriaTokenCodigo(String tesoreria_token_codigo) { this.tesoreria_token_codigo = tesoreria_token_codigo; }
public Date getTesoreriaTokenFecha() { return tesoreria_token_fecha; }
public void setTesoreriaTokenFecha(Date tesoreria_token_fecha) { this.tesoreria_token_fecha = tesoreria_token_fecha; }
public int getActivo() { return activo; }
public void setActivo(int activo) { this.activo = activo; }
#Override
public String toString() {
return "Id:" + id + ", " + "Perfil:" + perfil.getNombre() + ", " + "Id_Perfil:" + perfil.getId() + ", " + "Nombre:" + nombre + ", " + "Usuario:" + usuario + ", " + "Correo:" + correo + ", " + "Teléfono:" + telefono + ", " + "Image_Perfil:" + imagen_perfil + ", " + "Intranet_Id:" + intranet_id + ", " + "Intranet_Notaria:" + intranet_notaria + ", " + "Activo:" + activo;
}
}
The problem is that ${usr} is only displaying some of my attributes, but not all! I need to display all the attributes in my jsp.
Try using camelCase notation if you are not doing so. For example instead of ${usr.imagen_perfil} use ${usr.imagenPerfil}. I think it will be expecting to use the object getters getImagenPerfil().
for my college project, I am trying to implement a sectioned recyclerview with the section title as date, and a list of appointments as the contents, in each row of appointments I want to display some fields, in which I have created the apnmntDetails class as below:
public class apnmtDetails {
private String BarberName;
private String Barbershop;
private String ServiceName;
private String ServiceType;
private String Servicestatus;
private String ServicePrice;
private String ServiceTime;
public apnmtDetails(String barberName, String barbershop,
String serviceName, String serviceType,
String servicestatus, String servicePrice,
String serviceTime) {
BarberName = barberName;
Barbershop = barbershop;
ServiceName = serviceName;
ServiceType = serviceType;
Servicestatus = servicestatus;
ServicePrice = servicePrice;
ServiceTime = serviceTime;
}
public String getBarberName() {
return BarberName;
}
public void setBarberName(String barberName) {
BarberName = barberName;
}
public String getBarbershop() {
return Barbershop;
}
public void setBarbershop(String barbershop) {
Barbershop = barbershop;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String serviceName) {
ServiceName = serviceName;
}
public String getServiceType() {
return ServiceType;
}
public void setServiceType(String serviceType) {
ServiceType = serviceType;
}
public String getServicestatus() {
return Servicestatus;
}
public void setServicestatus(String servicestatus) {
Servicestatus = servicestatus;
}
public String getServicePrice() {
return ServicePrice;
}
public void setServicePrice(String servicePrice) {
ServicePrice = servicePrice;
}
public String getServiceTime() {
return ServiceTime;
}
public void setServiceTime(String serviceTime) {
ServiceTime = serviceTime;
}
#Override
public String toString() {
return "apnmtDetails{" +
"BarberName='" + BarberName + '\'' +
", Barbershop='" + Barbershop + '\'' +
", ServiceName='" + ServiceName + '\'' +
", ServiceType='" + ServiceType + '\'' +
", Servicestatus='" + Servicestatus + '\'' +
", ServicePrice='" + ServicePrice + '\'' +
", ServiceTime='" + ServiceTime + '\'' +
'}';
}}
after that, I created a section class that holds the field of the sectionName and sectionItem, where sectionitem is an arraylist of the apnmntDetails class, the code is below:
public class Section {
private String SectionName;
private ArrayList<apnmtDetails> SectionItem;
public Section(String sectionName, ArrayList<apnmtDetails> sectionItem) {
SectionName = sectionName;
SectionItem = sectionItem;
}
public String getSectionName() {
return SectionName;
}
public void setSectionName(String sectionName) {
SectionName = sectionName;
}
public ArrayList<apnmtDetails> getSectionItem() {
return SectionItem;
}
public void setSectionItem(ArrayList<apnmtDetails> sectionItem) {
this.SectionItem.addAll(sectionItem);
}
#Override
public String toString() {
return "Section{" +
"SectionName='" + SectionName + '\'' +
", SectionItem=" + SectionItem +
'}';
}}
Right now, in the activity, I initialize all the value by querying from firebase firestore:
private void initData(){
db.collection("appointmentsColl").document(UserId)
.collection("Date")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
db.collection("appointmentsColl").document(UserId)
.collection("Date").document(document.getId())
.collection("appointmentsID")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
for (DocumentSnapshot querysnapshot: task.getResult()){
apnmtDetails details = new apnmtDetails(querysnapshot.getString("barber"),
querysnapshot.getString("barber"),
querysnapshot.getString("name"),
querysnapshot.getString("type"),
querysnapshot.getString("status"),
querysnapshot.getString("price"),
querysnapshot.getString("time slot"));
apnmntList.add(details);
Log.i("apnmntList", apnmntList.toString());
}
}
});
sectionList.add(new Section(document.getString("date"),apnmntList));
}
for(int i = 0; i<sectionList.size(); i++)
Log.i("sectionList", sectionList.get(i).toString());
}else{
Toast.makeText(HomePage.this,"failed",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Check", e.toString() );
}
});
}
the problem is that when i try to print the value of the sectionlist, only the sectionName comes out correctly, whereas the appntmntDetails class's object did not appear as i want it to,
this is the logcat:
2021-03-04 14:57:06.748 4678-4678/com.example.homebarberv1 I/sectionList: Section{SectionName='4/AUG/2021', SectionItem=[]}
2021-03-04 14:57:07.029 4678-4678/com.example.homebarberv1 I/apnmntList: [apnmtDetails{BarberName='vAN7LYKoddRX2cQlogQtStOueKt2', Barbershop='vAN7LYKoddRX2cQlogQtStOueKt2', ServiceName='normal cut', ServiceType='Normal', Servicestatus='On hold', ServicePrice='4', ServiceTime='07:00 to 07:30'}]
firebase is not the problem as the value is retrieved correctly as shown in the logcat with the tag of apnmntList, but when printing the value using the servicelist arraylist, the value did not appear.
im still a bit unfamiliar and new with Java so, i will greatly appreciate if anyone can help in pointing out my mistake
You should call sectionList.add(new Section(document.getString("date"),apnmntList)); inside onComplete() call back method. Because this is a call back method is suspended and control jumps to execute code after call back code block. One more thing you should initialize apnmntList before for loop, because new list has to be saved for each Section.
I have made changes to onComplete() method, just have a look :
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
apnmntList = new ArrayList();
for (DocumentSnapshot querysnapshot: task.getResult()){
apnmtDetails details = new apnmtDetails(querysnapshot.getString("barber"),
querysnapshot.getString("barber"),
querysnapshot.getString("name"),
querysnapshot.getString("type"),
querysnapshot.getString("status"),
querysnapshot.getString("price"),
querysnapshot.getString("time slot"));
apnmntList.add(details);
Log.i("apnmntList", apnmntList.toString());
}
sectionList.add(new Section(document.getString("date"),apnmntList));
}
So I've made an app that should be able to search for an artist off the Spotify API. The response returns a 200 code. But the returned object is null. Meaning that either the response code should be 204 or that something is wrong with my class. The class is made with pojo and seems right.
I can't seem to figure out what is wrong.
Here are the code.
Artist Class
public class Artists {
#SerializedName("href")
#Expose
private String href;
#SerializedName("items")
#Expose
private List<Item> items;
#SerializedName("limit")
#Expose
private Integer limit;
#SerializedName("next")
#Expose
private String next;
#SerializedName("offset")
#Expose
private Integer offset;
#SerializedName("previous")
#Expose
private String previous;
#SerializedName("total")
#Expose
private Integer total;
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Object getPrevious() {
return previous;
}
public void setPrevious(String previous) {
this.previous = previous;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
#Override
public String toString() {
return "Artists{" +
"href='" + href + '\'' +
", items=" + items +
", limit=" + limit +
", next='" + next + '\'' +
", offset=" + offset +
", previous='" + previous + '\'' +
", total=" + total +
'}';
}
Item Class
public class Item {
#SerializedName("external_urls")
#Expose
private ExternalUrls externalUrls;
#SerializedName("followers")
#Expose
private Followers followers;
#SerializedName("genres")
#Expose
private List<String> genres;
#SerializedName("href")
#Expose
private String href;
#SerializedName("id")
#Expose
private String id;
#SerializedName("images")
#Expose
private List<Image> images;
#SerializedName("name")
#Expose
private String name;
#SerializedName("popularity")
#Expose
private Integer popularity;
#SerializedName("type")
#Expose
private String type;
#SerializedName("uri")
#Expose
private String uri;
public ExternalUrls getExternalUrls() {
return externalUrls;
}
public void setExternalUrls(ExternalUrls externalUrls) {
this.externalUrls = externalUrls;
}
public Followers getFollowers() {
return followers;
}
public void setFollowers(Followers followers) {
this.followers = followers;
}
public List<String> getGenres() {
return genres;
}
public void setGenres(List<String> genres) {
this.genres = genres;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPopularity() {
return popularity;
}
public void setPopularity(Integer popularity) {
this.popularity = popularity;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUri() {
return uri;
}
#Override
public String toString() {
return "Item{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", type='" + type + '\'' +
'}';
}
MainActivity
public void searchForArtist(View view) {
String q = "Justin Bieber";
TrackService trackService = ApiUtils.getTrackService();
Call<Artists> artistSearch = trackService.SearchForArtist("Bearer " + AuthToken, Accept, contentType, q, type, market, limit, offset);
Log.d("TEST", artistSearch.request().url().toString());
Log.d("TEST", " " + artistSearch.request().headers());
Log.d("Tokens", AuthToken);
Log.d("Tokens", " " + RefreshToken);
artistSearch.enqueue(new Callback<Artists>() {
#Override
public void onResponse(Call<Artists> call, Response<Artists> response) {
if (response.isSuccessful()) {
if (response.body().getItems() != null) {
Item artists = response.body().getItems().get(0);
artistID = artists.getId();
Toast.makeText(MainActivity.this, "Yeehaw", Toast.LENGTH_LONG).show();
searchForTracks(artistID);
} else {
Toast.makeText(MainActivity.this, "No content in Items", Toast.LENGTH_LONG).show();
Log.d("BODY",response.body().toString());
}
} else {
String message = "Problem " + response.code() + " " + response.body();
Log.d("Tracks", message);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Artists> call, Throwable t) {
Toast.makeText(MainActivity.this, "REEEEEEEE", Toast.LENGTH_LONG).show();
}
});
}
Posting JSON towards tomcat running Spring BOOT.
Mapping requests to update Mongo via Morphia
Getting Error : "status":500,"error":"Internal Server Error","exception":"org.bson.codecs.configuration.CodecConfigurationException","message":"Can't find a codec for class se.preffo.model.ProfileAccess.
Somehow it is not knowing how to create the Object ProfileAccess
ProfileClass
package se.preffo.model;
import java.util.List;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.*;
#Entity("profiles")
public class Profile extends BaseEntity {
#Property("user_name")
private String userName;
#Property("profile_data")
private List<ProfileData> profileData;
#Property("tags")
private List<String> profileTags;
#Property("profile_name")
private String profileName;
#Embedded
#Property("access")
private List<ProfileAccess> profileAccess;
public Profile (){
this.userName = "";
}
public String getUserName(){
return this.userName;
}
public void setUserName(String userId){
this.userName = userId;
}
public List<ProfileData> getProfileData(){
return this.profileData;
}
public void setProfileData(List<ProfileData> profileData){
this.profileData = profileData;
}
public String getProfileName() {
return profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
public List<ProfileAccess> getProfileAccess() {
return profileAccess;
}
public void setProfileAccess(List<ProfileAccess> profileAccess) {
this.profileAccess = profileAccess;
}
public List<String> getProfileTags() {
return profileTags;
}
public void setProfileTags(List<String> profileTags) {
this.profileTags = profileTags;
}
public void addTag(String tag){
this.profileTags.add(tag);
}
public void removeTag(String tag){
this.profileTags.remove(tag);
}
#Override
public String toString() {
return "Profile{" +
"id=" + id +
", userName='" + userName + '\'' +
", profileData=" + profileData +
", profileTags=" + profileTags +
", profileName='" + profileName + '\'' +
", profileAccess=" + profileAccess +
'}';
}
}
ProfileAccess class:
package se.preffo.model;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Property;
#Embedded
public class ProfileAccess{
#Property("name")
private String accessName;
#Property("access_id")
private String accessId;
#Property("exp")
private String expiryTime;
#Property("type")
private String accessType;
//Constructor
public ProfileAccess() {
super();
}
#Override
public String toString() {
return "ProfileAccess{" +
"accessName='" + accessName + '\'' +
", accessId='" + accessId + '\'' +
", expiryTime='" + expiryTime + '\'' +
", accessType='" + accessType + '\'' +
'}';
}
public String getAccessName() {
return accessName;
}
public void setAccessName(String accessName) {
this.accessName = accessName;
}
public String getAccessId() {
return accessId;
}
public void setAccessId(String accessId) {
this.accessId = accessId;
}
public String getExpiryTime() {
return expiryTime;
}
public void setExpiryTime(String expiryTime) {
this.expiryTime = expiryTime;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
ProfileController
// ---------------------- UPDATE LIST OF PROFILES
#RequestMapping(value="/profiles/batch", method=RequestMethod.POST)
public void updateProfile(#RequestBody List<Profile> profiles) {
logger.debug(profiles.get(0).toString());
profileService.updateProfiles(profiles);
}
ProfileService
public void updateProfiles(List<Profile> profiles) {
datastore = MongoDbHelper.INSTANCE.getDatastore();
for (Profile profile : profiles) {
logger.debug(profile.toString());
datastore.save(profile);
}
}
MongoDbHelper
private MongoDbHelper() {
MongoClient mongoClient = new MongoClient(new MongoClientURI("uritomongodb"));
Morphia morphia = new Morphia();
this.datastore = morphia.createDatastore(mongoClient, DATABASE_NAME);
}
public Datastore getDatastore() {
return this.datastore;
}
Posted JSON
[{"id":{"timestamp":1489743145,"machineIdentifier":13056160,"processIdentifier":3851,"counter":6420585,"time":1489743145000,"date":1489743145000,"timeSecond":1489743145},"version":14,"userName":"test#gmail.com","profileData":null,"profileTags":null,"profileName":"jonas","profileAccess":[{"accessId":"testare","expiryTime":"20170319","accessName":"testare","accessType":"shop"}]}]
I am working on Springboot REST API. My application should consume and produce both XML and JSON. I came across the Jackson json Xml dependency.
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.5.4</version>
</dependency>
I added this in my pom.xml. Now I am able to accept xml input but the values are null when mapped to Java Object. The following is my Resource class.
#Configuration
#ImportResource("/application-context.xml")
#EnableAutoConfiguration
#ResponseBody
#RequestMapping("/match")
public class MatchResource {
private static final Logger logger = LogManager.getLogger(MatchResource.class);
#Autowired
private MatchService matchService;
#RequestMapping(method = RequestMethod.POST)
#Consumes({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
#Produces({MediaType.TEXT_XML,MediaType.APPLICATION_JSON})
//#Produces( MediaType.APPLICATION_XML)
public Response matchRequest(#RequestBody MatchRequest matchRequest,
#Context HttpServletRequest headers) throws Exception {
Response resp = null;
MiniMatchResponse output = null;
// Headers are store in the "headers" object. To retrieve a specific header, please take a look at the below statement
String apiUser = headers.getHeader("Api-User");
UUID randID = UUID.randomUUID();
logger.info("Get Match for with ID: " + randID);
// Get service profile from headers via MatchConstants.SERVICE_PROFILE_HEADER
String serviceProfile = "";
try {
//TODO: MatchService should return MatchResponse Object
//Json OutPut
output = matchService.findResponse(matchRequest, serviceProfile);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
logger.debug("Match Request: " + matchRequest.toString());
} catch (ErrorException e) {
logger.error(e.getMessage(), e);
}
// Form Response
resp = Response.status(200).entity(output).build();
return resp;
}
The below is my Request Object
package com.infoconnect.api.dto.Match;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class MatchRequest implements Serializable {
// Gets or sets the RequestType of request this represents.
// Allowed values are "Company", "People" and "Any".
private String requestType;
private String name;
private String companyName;
private String streetAddress;
private String streetAddress2;
private String city;
private String stateProvince;
private String postalCode;
private String country;
private String serviceProfile;
private String resourceType;
private int limit;
private Integer confidence;
private String phone;
private Boolean includeHistorical;
private Boolean includeNonVerified;
private String requestId;
private List<String> fields;
public String getRequestType() {
return requestType;
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getStreetAddress2() {
return streetAddress2;
}
public void setStreetAddress2(String streetAddress2) {
this.streetAddress2 = streetAddress2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStateProvince() {
return stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getServiceProfile() {
return serviceProfile;
}
public void setServiceProfile(String serviceProfile) {
this.serviceProfile = serviceProfile;
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public Integer getConfidence() {
return confidence;
}
public void setConfidence(Integer confidence) {
this.confidence = confidence;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Boolean getIncludeHistorical() {
return includeHistorical;
}
public void setIncludeHistorical(Boolean includeHistorical) {
this.includeHistorical = includeHistorical;
}
public Boolean getIncludeNonVerified() {
return includeNonVerified;
}
public void setIncludeNonVerified(Boolean includeNonVerified) {
this.includeNonVerified = includeNonVerified;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public List<String> getFields() {
return fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
#Override
public String toString() {
return "MatchRequest{" +
"requestType='" + requestType + '\'' +
", name='" + name + '\'' +
", companyName='" + companyName + '\'' +
", streetAddress='" + streetAddress + '\'' +
", streetAddress2='" + streetAddress2 + '\'' +
", city='" + city + '\'' +
", stateProvince='" + stateProvince + '\'' +
", postalCode='" + postalCode + '\'' +
", country='" + country + '\'' +
", serviceProfile='" + serviceProfile + '\'' +
", resourceType='" + resourceType + '\'' +
", limit=" + limit +
", confidence=" + confidence +
", phone='" + phone + '\'' +
", includeHistorical=" + includeHistorical +
", includeNonVerified=" + includeNonVerified +
", requestId='" + requestId + '\'' +
", fields=" + fields +
'}';
}
}
JSON request and Response works fine. Can you please help me how to Include XML request and Response in my application.
Try to add a #XmlRootElement(name="myRootTag") JAXB annotation with the tag you use as the root tag to the class MatchRequest. I have had similar issues when using both XML and JSON as transport format in a REST request, but using moxy instead of Jackson. In any case, proper JAXB annotations are necessary to convert to/from XML (XML is much pickier in this respect than JSON).
Jackson XML is supposed to support JAXB annotations, and if this does not work, it has an own set of similar annotations that are incompatible to JAXB (see https://github.com/FasterXML/jackson-dataformat-xml and https://github.com/FasterXML/jackson-dataformat-xml/wiki/Jackson-XML-annotations)