I am trying to use GSON to convert a java object, in list format, to JSON, I have tried a few ways, but am running into the same error.
1st attempt
List<Techinv> techs = UserUtil.getTechModels(group, org);
Gson gson = new Gson();
String json = gson.toJson(techs);
2nd attempt
List<Techinv> techs = UserUtil.getTechModels(group, org);
Type listType = new TypeToken<List<Techinv>>() {}.getType();
Gson gson = new Gson();
String json = gson.toJson(techs, listType);
3rd attempt
List<Techinv> techs = UserUtil.getTechModels(group, org);
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
.addType(Techinv.class)
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = gson.toJson(techs);
All of the above fail, with either a stackoverflow error or a can't convert java int (one of the members in my Techinv class) to a java vector, all in the GSON library.
Please tell me I am missing something simple in all these examples :)
Techinv class (if required)
package org.cchit.inv.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The persistent class for the techinv database table.
*
*/
#Entity
#NamedNativeQueries ({
#NamedNativeQuery(name="Techinv.deleteByOrgId",
query="DELETE FROM techinv where org_id = ?")
})
#NamedQueries ({
#NamedQuery(name="Techinv.removeUser",
query="UPDATE Techinv t SET user_id = 0 where t.id = :techid"),
#NamedQuery(name="Techinv.getAllByOrg",
query="SELECT p FROM Techinv p where p.organization.liferayId = :orgid"),
#NamedQuery(name="Techinv.getById",
query="SELECT t FROM Techinv t where t.id = :id"),
#NamedQuery(name="Techinv.getByProdOrg",
query="SELECT p FROM Techinv p where p.organization.liferayId = :orgid and p.product.id = :prodid"),
#NamedQuery(name="Techinv.delete",
query="DELETE FROM Techinv t where t.id = :id")
})
#Table(name="techinv")
public class Techinv implements Serializable {
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="mu_mask")
private long muMask;
#Column(name="mu_assigned_mask")
private long muAssignedMask;
#Column(name="mu_asked_assign_mask")
private long muAskedAssignedMask;
#Column(name="mu_cert_mask")
private long muWillCertMask;
#Column(name="mu_ask_will_cert_mask")
private long muAskedWillCertMask;
#Column(name="certType")
private String certType;
#Temporal(TemporalType.DATE)
#Column(name="Apply_date")
private Date applyDate;
#Temporal(TemporalType.DATE)
#Column(name="Cert_date")
private Date certDate;
#Lob()
private String notes;
//bi-directional many-to-one association to OrgUser
#ManyToOne
#JoinColumn(name="user_id")
private OrgUser orgUser;
//bi-directional many-to-one association to Organization
#ManyToOne
#JoinColumn(name="org_id")
private Organization organization;
//bi-directional many-to-one association to Product
#ManyToOne
#JoinColumn(name="prod_id")
private Product product;
//bi-directional many-to-one association to Certification
#ManyToOne
#JoinColumn(name="cert_id")
private Certification certification;
public void setCertification(Certification certification) {
this.certification = certification;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Techinv() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public OrgUser getOrgUser() {
return this.orgUser;
}
public void setOrgUser(OrgUser orgUser) {
this.orgUser = orgUser;
}
public Organization getOrganization() {
return this.organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public long getMuMask() {
return muMask;
}
public void setMuMask(long muMask) {
this.muMask = muMask;
}
public long getMuAssignedMask() {
return muAssignedMask;
}
public void setMuAssignedMask(long muAssigned) {
this.muAssignedMask = muAssigned;
}
public Certification getCertification() {
return certification;
}
public long getMuWillCertMask() {
return muWillCertMask;
}
public void setMuWillCertMask(long muWillCertMask) {
this.muWillCertMask = muWillCertMask;
}
public long getMuAskWillCertMask() {
return muAskedWillCertMask;
}
public void setMuAskedWillCertMask(long muAskedWillCertMask) {
this.muAskedWillCertMask = muAskedWillCertMask;
}
/**
* This will set the question to true. Once asked and answered, this cannot be unset.
* #param mu
*/
public void setMuAskedAssignedMask(Mu mu) {
this.muAskedAssignedMask |= mu.getMask();
}
public boolean isCertified(Mu mu) {
return getCertification() != null && (getCertification().getMuMask() & mu.getMask()) > 0;
}
public boolean isAssigned(Mu mu) {
return (getMuAssignedMask() & mu.getMask()) > 0;
}
public boolean hasAskedToCertify(Mu mu) {
return isAssigned(mu) && !isCertified(mu) && (getMuAskWillCertMask() & mu.getMask()) > 0;
}
public boolean isWillCertify(Mu mu) {
return hasAskedToCertify(mu) && (getMuWillCertMask() & mu.getMask()) > 0;
}
public boolean hasMu(Mu mu) {
return (getMuMask() & mu.getMask()) > 0;
}
public boolean hasAskedToAssign(Mu mu) {
return (muAskedAssignedMask & mu.getMask()) > 0;
}
public String getCertType() {
return certType;
}
public void setCertType(String certType) {
this.certType = certType;
}
public Date getApplyDate() {
return applyDate;
}
public void setApplyDate(Date applyDate) {
this.applyDate = applyDate;
}
public Date getCertDate() {
return certDate;
}
public void setCertDate(Date certDate) {
this.certDate = certDate;
}
}
You should check for circular references in your serialized classes and mark the appropriate properties #Transient. Post your TechModel class if you want help with that.
edit: as using #Transient is not an option for you , use Gson's #Expose .
From the GSON user guide :
This feature provides a way where you can mark certain fields of your
objects to be excluded for consideration for serialization and
deserialization to JSON. To use this annotation, you must create Gson
by using new
GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The
Gson instance created will exclude all fields in a class that are not
marked with #Expose annotation.
Type listType = new TypeToken<ArrayList<Techinv>>() {}.getType();
You may try out the standard implementation of the Java API for JSON processing which is part of J2EE.
I don't have access to your beans OrgUser, Organization, Product, and Certification. So I assume that each of them comprises an id and a name.
For your List<Techinv> techList.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Techinv> techList = new ArrayList<Techinv>();
for (int i = 1; i <= 3; i++) {
Techinv tech = new Techinv(i, 1L, 2L, 3L, 4L, 5L, "cert",
new Date(), new Date(), "notes", new OrgUser(i, "orguser"),
new Organization(i, "organization"), new Product(i,
"product"), new Certification(i, "certification"));
techList.add(tech);
}
Techinv[] techArr = techList.toArray(new Techinv[techList.size()]);
JsonArrayBuilder techArrBuilder = Json.createArrayBuilder();
for (Techinv tech : techArr) {
JsonObjectBuilder jsonObject = Json.createObjectBuilder()
.add("id", tech.getId())
.add("muMask", tech.getMuMask())
.add("muAssignedMask", tech.getMuAssignedMask())
.add("muAskedAssignedMask", tech.getMuAskedAssignedMask())
.add("muWillCertMask", tech.getMuWillCertMask())
.add("muAskedWillCertMask", tech.getMuAskedWillCertMask())
.add("certType", tech.getCertType())
.add("applyDate", sdf.format(tech.getApplyDate()))
.add("certDate", sdf.format(tech.getCertDate()))
.add("notes", tech.getNotes())
.add("OrgUser", Json.createObjectBuilder()
.add("id", tech.getOrgUser().getId())
.add("name", tech.getOrgUser().getName()))
.add("Organization", Json.createObjectBuilder()
.add("id", tech.getOrganization().getId())
.add("name", tech.getOrganization().getName()))
.add("Product", Json.createObjectBuilder()
.add("id", tech.getProduct().getId())
.add("name", tech.getProduct().getName()))
.add("Certification", Json.createObjectBuilder()
.add("id", tech.getCertification().getId())
.add("name", tech.getCertification().getName()));
techArrBuilder.add(jsonObject);
}
JsonArray jsonArray = techArrBuilder.build();
Map<String, Object> prop = new HashMap<String, Object>() {
{
put(JsonGenerator.PRETTY_PRINTING, true);
}
};
JsonWriter jsonWriter = Json.createWriterFactory(prop).createWriter(System.out);
jsonWriter.writeArray(jsonArray);
jsonWriter.close();
The output should be:
[
{
"id":1,
"muMask":1,
"muAssignedMask":2,
"muAskedAssignedMask":3,
"muWillCertMask":4,
"muAskedWillCertMask":5,
"certType":"cert",
"applyDate":"2014-04-03",
"certDate":"2014-04-03",
"notes":"notes",
"OrgUser":{
"id":1,
"name":"orguser"
},
"Organization":{
"id":1,
"name":"organization"
},
"Product":{
"id":1,
"name":"product"
},
"Certification":{
"id":1,
"name":"certification"
}
},
{
"id":2,
"muMask":1,
"muAssignedMask":2,
"muAskedAssignedMask":3,
"muWillCertMask":4,
"muAskedWillCertMask":5,
"certType":"cert",
"applyDate":"2014-04-03",
"certDate":"2014-04-03",
"notes":"notes",
"OrgUser":{
"id":2,
"name":"orguser"
},
"Organization":{
"id":2,
"name":"organization"
},
"Product":{
"id":2,
"name":"product"
},
"Certification":{
"id":2,
"name":"certification"
}
},
{
"id":3,
"muMask":1,
"muAssignedMask":2,
"muAskedAssignedMask":3,
"muWillCertMask":4,
"muAskedWillCertMask":5,
"certType":"cert",
"applyDate":"2014-04-03",
"certDate":"2014-04-03",
"notes":"notes",
"OrgUser":{
"id":3,
"name":"orguser"
},
"Organization":{
"id":3,
"name":"organization"
},
"Product":{
"id":3,
"name":"product"
},
"Certification":{
"id":3,
"name":"certification"
}
}
]
Related
The result coming from an external API as..
BIBREF are dynamic, the we do not know how will be fetched
The index is appended to the name "BIBREF+number"
"bib_entries": {
"BIBREF0": {
"ref_id": <str>,
"title": <str>,
},
"BIBREF1": {
"ref_id": <str>,
"title": <str>,
},
...
...
"BIBREF25": {}
},
Defined a pojo as..
public class BibEntries {
private BibRef bibRef;
# ...getters/setters
public class BibRef {
private String ref_id;
private String title;
# ...getters/setters
}
}
Defined the class as:
JsonObject bibEntriesObject = jsonObject.get("bib_entries").getAsJsonObject();
BibEntries bibEntries = new Gson().fromJson(bibEntriesObject, BibEntries.class);
Learning GSON and using GenericTypes seemed confusing. How can i update the above code to read the dynamic objects (using gson 2.8.6)?
With some help from my colleague, here's the solution
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static final Gson gson = new
GsonBuilder().serializeNulls().setPrettyPrinting().create();
public static void main(String[] args) {
// Original Json Input
String jsonRequest = "{ \"bib_entries\": { \"BIBREF0\": { \"ref_id\": \"One\", \"title\": \"two\"},"
+ "\"BIBREF1\": { \"ref_id\": \"three\", \"title\": \"four\"} } }";
//Convert string to JsonObject
JsonObject convertedObject = new Gson().fromJson(jsonRequest, JsonObject.class);
JsonObject object = convertedObject.get("bib_entries").getAsJsonObject();
//Init Class
BibEntries bibEntries = new BibEntries();
List<BibEntries.Bibref> list = new ArrayList<>();
//Mapping the object to class
object.keySet().stream().forEach((key) -> {
// We can add more here..
BibEntries.Bibref bibref = gson.fromJson(object.get(key), BibEntries.Bibref.class);
list.add(bibref);
bibEntries.setListBibref(list);
});
//Original
System.out.println(convertedObject);
// Print the final result
System.out.println(gson.toJson(bibEntries));
}
public static class BibEntries {
List<Bibref> listBibref;
public static class Bibref {
#SerializedName("ref_id")
private String refId;
#SerializedName("title")
private String title;
public String getRefId() {
return refId;
}
public void setRefId(final String refId) {
this.refId = refId;
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
}
public List<Bibref> getListBibref() {
return listBibref;
}
public void setListBibref(final List<Bibref> listBibref) {
this.listBibref = listBibref;
}
}
}
i have i a class StudentAdmissinAssoDTO that have Other class references
as below
StudentAdmissinAssoDTO
package com.rasvek.cg.entity;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class StudentAdmissinAssoDTO
{
private PrimaryStudentAdmission primaryAdmission;
private StudentDetails studentDetailsDto;
private StudentJoiningDetails studentJoiningDetails;
private StudentPresentClassDetails studentPresentClassDetails;
private StudentGeneralDetails studentGeneralDetails;
private StudentPrevSchoolDetails studentPrevSchoolDetails;
private StudentParentDetails studentParentDetails;
private MasterAddress masterAddress;
private List<AssocFeeStudent> assocFeeStudentId;
public StudentDetails getStudentDetailsDto() {
return studentDetailsDto;
}
public void ListStudentDetailsDto(StudentDetails studentDetailsDto) {
this.studentDetailsDto = studentDetailsDto;
}
public PrimaryStudentAdmission getPrimaryAdmission() {
return primaryAdmission;
}
public void ListPrimaryAdmission(PrimaryStudentAdmission primaryAdmission) {
this.primaryAdmission = primaryAdmission;
}
public StudentJoiningDetails getStudentJoiningDetails() {
return studentJoiningDetails;
}
public void ListStudentJoiningDetails(StudentJoiningDetails studentJoiningDetails) {
this.studentJoiningDetails = studentJoiningDetails;
}
public StudentPresentClassDetails getStudentPresentClassDetails() {
return studentPresentClassDetails;
}
public void ListStudentPresentClassDetails(StudentPresentClassDetails studentPresentClassDetails) {
this.studentPresentClassDetails = studentPresentClassDetails;
}
public StudentGeneralDetails getStudentGeneralDetails() {
return studentGeneralDetails;
}
public void ListStudentGeneralDetails(StudentGeneralDetails studentGeneralDetails) {
this.studentGeneralDetails = studentGeneralDetails;
}
public StudentPrevSchoolDetails getStudentPrevSchoolDetails() {
return studentPrevSchoolDetails;
}
public void ListStudentPrevSchoolDetails(StudentPrevSchoolDetails studentPrevSchoolDetails) {
this.studentPrevSchoolDetails = studentPrevSchoolDetails;
}
public StudentParentDetails getStudentParentDetails() {
return studentParentDetails;
}
public void ListStudentParentDetails(StudentParentDetails studentParentDetails) {
this.studentParentDetails = studentParentDetails;
}
public MasterAddress getMasterAddress() {
return masterAddress;
}
public void ListMasterAddress(MasterAddress masterAddress) {
this.masterAddress = masterAddress;
}
public List<AssocFeeStudent> getAssocFeeStudentId() {
return assocFeeStudentId;
}
public void ListAssocFeeStudentId(List<AssocFeeStudent> assocFeeStudentId) {
this.assocFeeStudentId = assocFeeStudentId;
}
}
and i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter):
[org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]]
please look at MasterAddress
package com.rasvek.cg.entity;
//Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
/**
* MasterAddress generated by hbm2java
*/
#Entity
#Table(name = "master_address", catalog = "campus_guru_01")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "addressId")
public class MasterAddress implements java.io.Serializable {
private Integer addressId;
private Integer studentAdmissionId;
private String isSame;
private MasterAddressCountry masterAddressCountry;
private MasterAddressDistrict masterAddressDistrict;
private MasterAddressState masterAddressState;
private String houseNum;
private String streetAddress;
private String citymandal;
private String pincode;
private String addressType;
private Set<AssocStaffAddress> assocStaffAddresses = new HashSet<AssocStaffAddress>(0);
private Set<AssocStudentAddress> assocStudentAddresses = new HashSet<AssocStudentAddress>(0);
public MasterAddress() {
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict,
MasterAddressState masterAddressState) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict, MasterAddressState masterAddressState, String houseNum, String streetAddress, String citymandal, String pincode, String addressType, Set<AssocStaffAddress> assocStaffAddresses, Set<AssocStudentAddress> assocStudentAddresses) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
this.houseNum = houseNum;
this.streetAddress = streetAddress;
this.citymandal = citymandal;
this.pincode = pincode;
this.addressType = addressType;
this.assocStaffAddresses = assocStaffAddresses;
this.assocStudentAddresses = assocStudentAddresses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "address_id", unique = true, nullable = false)
public Integer getAddressId() {
return this.addressId;
}
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "country_id", nullable = false)
public MasterAddressCountry getMasterAddressCountry() {
return this.masterAddressCountry;
}
public void setMasterAddressCountry(MasterAddressCountry masterAddressCountry) {
this.masterAddressCountry = masterAddressCountry;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "district_id", nullable = false)
public MasterAddressDistrict getMasterAddressDistrict() {
return this.masterAddressDistrict;
}
public void setMasterAddressDistrict(MasterAddressDistrict masterAddressDistrict) {
this.masterAddressDistrict = masterAddressDistrict;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "state_id", nullable = false)
public MasterAddressState getMasterAddressState() {
return this.masterAddressState;
}
public void setMasterAddressState(MasterAddressState masterAddressState) {
this.masterAddressState = masterAddressState;
}
#Column(name = "house_num", length = 45)
public String getHouseNum() {
return this.houseNum;
}
public void setHouseNum(String houseNum) {
this.houseNum = houseNum;
}
#Column(name = "street_address", length = 45)
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
#Column(name="citymandal")
public String getCitymandal() {
return this.citymandal;
}
public void setCitymandal(String citymandal) {
this.citymandal = citymandal;
}
#Column(name = "pincode", length = 45)
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
#Column(name = "address_type", length = 9)
public String getAddressType() {
return this.addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStaffAddress> getAssocStaffAddresses() {
return this.assocStaffAddresses;
}
public void setAssocStaffAddresses(Set<AssocStaffAddress> assocStaffAddresses) {
this.assocStaffAddresses = assocStaffAddresses;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStudentAddress> getAssocStudentAddresses() {
return this.assocStudentAddresses;
}
public void setAssocStudentAddresses(Set<AssocStudentAddress> assocStudentAddresses) {
this.assocStudentAddresses = assocStudentAddresses;
}
#Column(name="student_admission_id")
public Integer getStudentAdmissionId() {
return studentAdmissionId;
}
public void setStudentAdmissionId(Integer studentAdmissionId) {
this.studentAdmissionId = studentAdmissionId;
}
#Column(name="is_same")
public String getIsSame() {
return isSame;
}
public void setIsSame(String isSame) {
this.isSame = isSame;
}
}
there is no dependency Dependency Between StudentAdmissinAssoDTO and MasterAddress .
i am just using StudentAdmissinAssoDTO to make nested json objects .
so that i can get them in the controller
like bellow
MasterAddress masterAddress =null;
masterAddress = studentAdmissinAssoDTO.getMasterAddress();
why i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter): [org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]
can any one Explain why its happening so. thank you!.
i found my mistake there was i misplace of #JsonManagedReference in MasterDistrict Class of MasterAddress
PlayerService
this is srvice class of my boot app.
package io.anuj.springbootquickstart.topic;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class PlayerService {
#Autowired
private PlayerRespository playerRespository;
// private List<Topic> topics = new ArrayList<> (Arrays.asList(
// new Topic("Spring","Spring Framework","SpringFramework Description"),
// new Topic("Core","Core Framework","CoreFramework Description"),
// new Topic("JavaScript","JavaScript Framework","JavaScript Description")));
public List<Player> getAllPlayer(){
List<Player> player = new ArrayList();
playerRespository.findAll()
.forEach(player::add); //lambda expressions
return player;
}
public Player getPlayer(Long id){
//return topics.stream().filter(t -> t.getId().equals(id).findFirst().get());
return playerRespository.findOne(id);
}
public void addPlayer(Player player) {
playerRespository.save(player);
}
public void updatePlayer(Long id, Player player) {
playerRespository.save(player);
}
public void deletePlayer(Long id) {
//topics.removeIf(t -> t.getId().equals(id));
playerRespository.delete(id);
}
}
PLayerRepository
this is player repository of my app.
package io.anuj.springbootquickstart.topic;
import org.springframework.data.repository.CrudRepository;
public interface PlayerRespository extends CrudRepository <Player, Long>{
//crud repository-logic of any entity class
//getallTopic()
//gettopic(string id)
//update topic(topic t)
//deletetopic(string id)
}
PLayerController
this is player controller
package io.anuj.springbootquickstart.topic;
import java.io.FileReader;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
//wherever rest controller is written it will give json as output send back as a HTTP response
public class PlayerController {
#Autowired
private PlayerService playerService;
//get request by default
#RequestMapping("/player")
public List<Player> getallPlayer(){
return playerService.getAllPlayer();
}
//get request
#RequestMapping("/player/{id}")
public Player getPlayer(#PathVariable Long id){
return playerService.getPlayer(id);
}
//
#RequestMapping(method=RequestMethod.GET, value= "/getplayer")
public void addAllPlayer(){
Player player = new Player();
JSONParser parser = new JSONParser();
try {
Object ob = parser.parse(new FileReader("/home/bridgeit/Desktop/P.D-anuj/Json/newPlayerInfo.json"));
JSONObject object = (JSONObject) ob;
JSONArray data = (JSONArray) object.get("Playersinfo");
for (int i = 0; i < data.size(); i++)
{
JSONObject itemObj = (JSONObject) data.get(i);
Object nameObj = itemObj.get("player_name");
String playerName = (String) nameObj;
player.setPlayer_name(playerName);
Object imgObject = itemObj.get("player_img_url");
String playerPic = (String) imgObject;
player.setPlayer_img_url(playerPic);
Object roleObj = itemObj.get("player_role");
String roleName = (String) roleObj;
player.setPlayer_role(roleName);
Object battingStyleObj = itemObj.get("player_batting_style");
String battingStyleName = (String) battingStyleObj;
player.setPlayer_batting_style(battingStyleName);
Object bowlingObj = itemObj.get("player_bowling_style");
String bowlingName = (String) bowlingObj;
player.setPlayer_bowling_style(bowlingName);
Object nationalityObj = itemObj.get("player_nationality");
String nationalityName = (String) nationalityObj;
player.setPlayer_nationality(nationalityName);
Object dobObj = itemObj.get("player_dob");
String dobName = (String) dobObj;
player.setPlayer_dob(dobName);
Object teamIdObj = itemObj.get("team_id");
String teamIdName = (String) teamIdObj;
player.setTeam_id(teamIdName);
playerService.addPlayer(player);
}
} catch (Exception e) {
System.out.println(e);
}
}
/*#RequestMapping(method=RequestMethod.PUT, value= "/player/{id}")
public void updatePlayer(#RequestBody Player player,#PathVariable String id){
playerService.updatePlayer(id,player);
}
#RequestMapping(method=RequestMethod.DELETE, value= "/player/{id}")
public void deletePlayer(#PathVariable String id){
playerService.deletePlayer(id);
}*/
}
this is POJO class
Player.java
package io.anuj.springbootquickstart.topic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
#Entity
/*#Table(name = "Player")*/
public class Player {
/*#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
#Column(name = "id")
private Long id;*/
#Id
#GenericGenerator(name = "gene", strategy = "increment")
#GeneratedValue(generator = "gene")
private long id;
private String team_id;
/*#Column(name = "name")*/
private String player_name;
/*#Column(name = "display_picture")*/
private String player_img_url;
/*#Column(name = "role")*/
private String player_role;
public Player(long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
/* #Column(name = "batting_style")*/
private String player_batting_style;
/*#Column(name = "bowling_style")*/
private String player_bowling_style;
/*#Column(name = "nationality")*/
private String player_nationality;
/*#Column(name = "dob")*/
private String player_dob;
/*#Column(name = "teamId")*/
public Player(){
}
public String getTeam_id() {
return team_id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public void setTeam_id(String team_id) {
this.team_id = team_id;
}
public String getPlayer_name() {
return player_name;
}
public void setPlayer_name(String player_name) {
this.player_name = player_name;
}
public String getPlayer_img_url() {
return player_img_url;
}
public void setPlayer_img_url(String player_img_url) {
this.player_img_url = player_img_url;
}
public String getPlayer_role() {
return player_role;
}
public void setPlayer_role(String player_role) {
this.player_role = player_role;
}
public String getPlayer_batting_style() {
return player_batting_style;
}
public void setPlayer_batting_style(String player_batting_style) {
this.player_batting_style = player_batting_style;
}
public String getPlayer_bowling_style() {
return player_bowling_style;
}
public void setPlayer_bowling_style(String player_bowling_style) {
this.player_bowling_style = player_bowling_style;
}
public String getPlayer_nationality() {
return player_nationality;
}
public void setPlayer_nationality(String player_nationality) {
this.player_nationality = player_nationality;
}
public String getPlayer_dob() {
return player_dob;
}
public void setPlayer_dob(String player_dob) {
this.player_dob = player_dob;
}
/*public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}*/
/*public Player(Long id, String team_id, String player_name, String player_img_url, String player_role,
String player_batting_style, String player_bowling_style, String player_nationality, String player_dob) {
super();
this.id = id;
this.team_id = team_id;
this.player_name = player_name;
this.player_img_url = player_img_url;
this.player_role = player_role;
this.player_batting_style = player_batting_style;
this.player_bowling_style = player_bowling_style;
this.player_nationality = player_nationality;
this.player_dob = player_dob;
}
*/
}
When i execute from json file it shows only last entry of json file. JSON file contains around 150 players but in databse is shows only last entry of the player. i think all the data is getting overwritten. Only last entry is shown of that json file in database. That is last player. Only one player which is last in json is there in database.
It's a little difficult to tell because you have a lot of commented out code that makes things harder to follow, but I think it is because of where you are creating the Player in your controller. Since you're doing this:
Player player = new Player()
outside of the loop, and Java is pass by value of reference, after the first time you addPlayer, you're just updating the same player with new data each time. You could confirm this if you simply debug your code and see if player has an ID after the first save call.
You'd probably want to do this to fix it:
for (int i = 0; i < data.size(); i++) {
Player player = new Player();
// rest of your code here
}
I have a problem with my adapter. I already succeeded to display some informations from my JSON (codeLieu and libelle) that looks like this:
[
{
"codeLieu": "OTAG",
"libelle": "50 Otages",
"distance": null,
"ligne": [
{
"numLigne": "2"
},
{
"numLigne": "C2"
},
{
"numLigne": "12"
},
{
"numLigne": "23"
}
]
},
...
]
Here is my model:
package material.romain.com.projentreprise.Adapter;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class Response implements Serializable{
private String codeLieu;
private String libelle;
private String distance;
private List<LigneEntities> ligne;
public String getCode() {
return codeLieu;
}
public void setCode(String codeLieu) {
this.codeLieu = codeLieu;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public List<LigneEntities> getLigne() {return ligne;}
public void setLigne(List<LigneEntities> ligne) {
this.ligne = ligne;
}
public static class LigneEntities {
private String numLigne;
public String getLigne() {
return numLigne;
}
public void setLigne(String numLigne) {
this.numLigne = numLigne;
}
}
}
And finally this is my adapter :
package material.romain.com.projentreprise.Adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.iconics.IconicsDrawable;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import material.romain.com.projentreprise.R;
import material.romain.com.projentreprise.Util.CircularTextView;
import material.romain.com.projentreprise.Util.ColorLigne;
public class ListAdapter extends BaseAdapter implements Filterable {
private ArrayList<Response> arret;
private Context context;
private LayoutInflater inflater;
private MyFilter mFilter;
private ArrayList<Response> mSearchArret;
public ListAdapter(Context mContext, ArrayList<Response> mArretItem) {
this.context = mContext;
this.arret = mArretItem;
this.mSearchArret = mArretItem;
getFilter();
}
#Override
public int getCount() {
return mSearchArret.size();
}
#Override
public Object getItem(int position) {
return mSearchArret.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Response item = (Response) getItem(position);
ColorLigne.ViewHolder holder = null;
if (convertView == null) {
holder = new ColorLigne.ViewHolder();
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.each_list_item, parent, false);
holder.circleImage = (CircleImageView) convertView.findViewById(R.id.circleView);
holder.textArret = (TextView) convertView.findViewById(R.id.tvListArret);
holder.circle = (CircularTextView) convertView.findViewById(R.id.tvArretColor);
convertView.setTag(holder);
} else {
holder = (ColorLigne.ViewHolder) convertView.getTag();
}
Drawable color = new ColorDrawable(ContextCompat.getColor(context, R.color.tanVert));
Drawable image = new IconicsDrawable(context).icon(FontAwesome.Icon.faw_bus).color(Color.WHITE).sizeDp(48).paddingDp(10);
LayerDrawable ld = new LayerDrawable(new Drawable[]{color, image});
holder.circleImage.setImageDrawable(ld);
holder.textArret.setText(item.getLibelle());
return convertView;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyFilter();
}
return mFilter;
}
class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (prefix != null && prefix.length() > 0) {
ArrayList<Response> tempList = new ArrayList<>();
for (Response value : arret) {
if (value.getLibelle().toLowerCase().contains(prefix.toString().toLowerCase())) {
tempList.add(value);
}
}
results.count = tempList.size();
results.values = tempList;
} else {
results.count = arret.size();
results.values = arret;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
try {
mSearchArret = (ArrayList<Response>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And I would like to get strings from "ligne" but it's in a list and I don't know how to access it. My goal is to put the strings into a circleTextView.
Edit:
I tried this in getView method
Response item = getItem(position);
for(Response value: arret){
value = item;
String ligneItem = value.getLigne().toString();
ColorLigne.setColorLigne(ligneItem, holder, context);
holder.circle.setText(ligneItem);
holder.circle.setStrokeWidth(0);
}
Add below method to your Response.java
public String getItems() {
StringBuilder builder = new StringBuilder();
for (LigneEntities entity : getLigne()) { //loop through every item from the list
builder.append(entity.getLigne() + ","); //add to StringBuilder
}
builder.replace(builder.length() - 1, builder.length(), "");//remove last ,(semicolon)
return builder.toString();
}
setting to your CircleTextView
holder.circle.setText(item.getItems());
I am new to Neo4j and I want to connect a node (Person) with a node (Asset) but also, store the time that this connection has been created. I figured out that I have to use #RelatedtoVia annotation. I have followed the Spring cineasts tutorial ([https://github.com/spring-projects/spring-data-neo4j/tree/master/spring-data-neo4j-examples/cineasts][1] ) Although, everything works fine as far as the tests and the database population are concerned, I get weird results at the REST service. Here is my code:
Node Person
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import org.springframework.data.neo4j.template.Neo4jOperations;
import java.util.*;
#NodeEntity
public class Person {
#GraphId
Long id;
#Indexed
private String displayName;
#Indexed(unique = true, failOnDuplicate = true)
private Long personId;
private String firstName;
private String lastName;
private Date birthday;
private String aboutMe;
private String thumbnailURL;
private String email;
private enum gendertypes {male, female, other};
private gendertypes gender;
private String[] languages;
private boolean active;
public static final String CONSUMED = "CONSUMED";
//empty & full constructor
//getters&setters
#RelatedToVia(type = "CONSUMED", elementClass = ConsumedDate.class)
#Fetch
Iterable<ConsumedDate> consumedDates;
public ConsumedDate consumedDate(Neo4jOperations template, Asset asset, Date timestamp) {
final ConsumedDate consumedDate = template.createRelationshipBetween(this, asset, ConsumedDate.class, CONSUMED, false).consumedDate(timestamp);
return template.save(consumedDate);
}
public Collection<ConsumedDate> getConsumedDates() {
return IteratorUtil.asCollection(consumedDates);
}
}
Node Asset
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import static org.neo4j.graphdb.Direction.INCOMING;
#NodeEntity
public class Asset {
#GraphId
private Long id;
#Indexed(unique=true, failOnDuplicate = true)
private Long assetId;
private String description;
private String type;
private String[] tags;
public Asset() {}
public Asset(Long assetId, String description, String type, String[] tags) {
this.assetId = assetId;
this.description = description;
this.type = type;
this.tags = tags;
}
public Long getAssetId() {return assetId; }
public void setAssetId(Long assetId) {
this.assetId = assetId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#RelatedTo(type = "CONSUMED", direction = INCOMING)
Set<Person> persons;
#RelatedToVia(type="CONSUMED", elementClass=ConsumedDate.class, direction=INCOMING)
#Fetch
Iterable<ConsumedDate> consumedDates;
public Collection<Person> getPersons() {
return persons;
}
public Collection<ConsumedDate> getConsumedDates() {
Iterable<ConsumedDate> allConsumedDates = consumedDates;
return allConsumedDates == null ? Collections.<ConsumedDate>emptyList() : IteratorUtil.asCollection(allConsumedDates);
}
#Override
public String toString() {
return "An asset with ID " + assetId + " description " + description + " type " + type;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Asset asset = (Asset) o;
if (id == null) return super.equals(o);
return id.equals(asset.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Relationship Entity ConsumedDate
import org.springframework.data.neo4j.annotation.EndNode;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.RelationshipEntity;
import org.springframework.data.neo4j.annotation.StartNode;
import java.util.Date;
#RelationshipEntity(type = "CONSUMED")
public class ConsumedDate {
#GraphId
Long id;
#EndNode
Asset asset;
#StartNode
Person person;
Date timestamp;
public ConsumedDate consumedDate(Date timestamp){
this.timestamp=timestamp;
return this;
}
public Asset getAsset() {
return asset;
}
public Person getPerson() {
return person;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConsumedDate consumedDate = (ConsumedDate) o;
if (id == null) return super.equals(o);
return id.equals(consumedDate.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Controller
import gr.ntua.sam.context.neo4j.AssetRepository;
import gr.ntua.sam.context.neo4j.LocationRepository;
import gr.ntua.sam.context.neo4j.PersonRepository;
import gr.ntua.sam.context.resources.*;
import com.wordnik.swagger.annotations.ApiOperation;
import org.neo4j.graphdb.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.*;
import java.util.List;
#RestController
#Configuration
#EnableNeo4jRepositories
public class ContextController {
#Autowired
Neo4jTemplate template;
#Autowired
AssetRepository assetRepository;
#Autowired
PersonRepository personRepository;
#ApiOperation(value = "Show the available assets", response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.GET)
public ResponseEntity<List<Asset>> getAssets() throws NotFoundException {
List<Asset> results = assetRepository.all();
return new ResponseEntity<List<Asset>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Create a new asset",response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Asset> saveAsset(#RequestBody Asset asset) {
Asset savedAsset = assetRepository.save(asset);
return new ResponseEntity<Asset>(savedAsset, HttpStatus.CREATED);
}
//Persons
#ApiOperation(value = "Get a list of all the available Persons")
#RequestMapping(value = "/person", method = RequestMethod.GET)
public ResponseEntity<List<Person>> getPersons() throws ParseException {
List<Person> results = personRepository.all();
return new ResponseEntity<List<Person>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Creates a new Person node to store information about a user", response = Person.class)
#RequestMapping(value = "/person", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Person> savePerson(#RequestBody Person person) {
Person savedPerson = personRepository.save(person);
return new ResponseEntity<Person>(savedPerson, HttpStatus.CREATED);
}
#ApiOperation(value = "Creates relationship between a Person and an Asset")
#RequestMapping(value = "/person/{personId}/consumes/", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> consumes(#PathVariable("personId") Long personId, #RequestBody LinkedAsset linkedAsset) {
Person person = personRepository.findByPersonId(personId);
List<Long> assetIds = linkedAsset.getAssetIDs();
for (Long assetId : assetIds) {
Asset currentAsset = assetRepository.findByAssetId(assetId);
Date date= linkedAsset.getTimestamp();
ConsumedDate consumedDate= person.consumedDate(template,currentAsset,date);
template.save(consumedDate);
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
The problem is that when I create a relationship between a Person and an Asset, along with a timestamp (I have created the class LinkedAsset which serves as a JSON input model and has nothing to do with Neo4j) and then try to get through REST the person or the asset, all I get is something definitely not JSON with the person or the asset appearing infinite times. Is there a way to face this problem?
Thank you in advance!