Issue parsing json with jackson 1.9 - java

I used Gson before and everything worked fine, but it is too slow.
Here is the Json:
"{"Info":[{"par1":3456,"par2":4500,"par3":0,"items":{"parx":2354,"pary":456456,"parz":"worker"}}
,{"par1":34456,"par2":4300,"par3":1,"items":{"parx":5677,"pary":78456,"parz":"member"}},
],"par4":343434,"duplicateItemIdList":null,"errorState":null}"
Now I tried Jackson:
code snippets:
ObjectMapper mapper = new ObjectMapper();
Passes mj = mapper.readValue(str, Passes.class);
public class Passes {
public ArrayList<Info> info;
.... }
#JsonIgnoreProperties(ignoreUnknown = true)
class Info {
public String par1 = "";
public String par2 = "";
public String par3 = "";
public String par4 = "";
Items items = new Items();
}
class Items{
public String parx = "";
public String pary = "";
public String parz = "";
}
the Problem is it doesn't fill the class items. parx,pary,parz etc
items is the only problem. the rest works fine.
my structure has to be right because in Gson I only need two lines and it works perfectly.
so I think I have to add something so that jackson recognizes

Be sure that you have:
geters/setters for each parameter
empty (or any ) Contractor
Passes
#JsonIgnoreProperties(ignoreUnknown = true)
public class Passes {
private List<Info> info;
public Passes() {
// TODO Auto-generated constructor stub
}
public List<Info> getInfo() {
return info;
}
public void setInfo(List<Info> info) {
this.info = info;
}
}
Info
#JsonIgnoreProperties(ignoreUnknown = true)
public class Info {
private int par1;
private int par2;
private int par3;
private int par4;
//private Items items;
public Info() {
// TODO Auto-generated constructor stub
}
public int getPar1() {
return par1;
}
public void setPar1(int par1) {
this.par1 = par1;
}
public int getPar2() {
return par2;
}
public void setPar2(int par2) {
this.par2 = par2;
}
public int getPar3() {
return par3;
}
public void setPar3(int par3) {
this.par3 = par3;
}
public int getPar4() {
return par4;
}
public void setPar4(int par4) {
this.par4 = par4;
}
}
Items
public class Items{
private int parx;
private int pary;
private String parz;
public Items() {
// TODO Auto-generated constructor stub
}
public int getParx() {
return parx;
}
public void setParx(int parx) {
this.parx = parx;
}
public int getPary() {
return pary;
}
public void setPary(int pary) {
this.pary = pary;
}
public String getParz() {
return parz;
}
public void setParz(String parz) {
this.parz = parz;
}
}
It should work
As a side note:
Gson uses LinkedLIst when Jackson ArrayList therefore from your code Gson fail to convert Passes class

Related

How print the entire data structure created with Composite?

I have class-Composite:
public class CompositeText implements ComponentText {
private TypeComponent type;
private String value;
private final List<ComponentText> childComponents;
private CompositeText() {
childComponents = new ArrayList<>();
}
public CompositeText(String value, TypeComponent typeComponent) {
this.value = value;
this.type = typeComponent;
childComponents = new ArrayList<>();
}
#Override
public void add(ComponentText componentText) {
childComponents.add(componentText);
}
#Override
public void remove(ComponentText componentText) {
childComponents.remove(componentText);
}
#Override
public TypeComponent getComponentType() {
return this.type;
}
#Override
public ComponentText getChild(int index) {
return childComponents.get(index);
}
#Override
public int getCountChildElements() {
return childComponents.size();
}
#Override
public int getCountAllElements() {
return childComponents.stream()
.mapToInt(ComponentText::getCountAllElements)
.sum();
}
#Override
public String toString() {
return null;
}
}
I created classes that perform the same action - parsing, parsing text into paragraphs, into sentences, into tokens, into symbols.
public class IntoParagraphParser implements ActionParser {
// call IntoSentenceParser
}
public class IntoSentenceParser implements ActionParser {
// call IntoLexemeParser
}
public class IntoLexemeParser implements ActionParser {
// call IntoSymbolParser
}
public class IntoSymbolParser implements ActionParser {
}
All data is stored in List <ComponentText> childComponents in class-Composite - CompositeText.
How to properly create a method so that it prints all the data that is inside the composite?
I think this will be the method toString() in CompositeText.
Class IntoParagraphParser look:
public class IntoParagraphParser implements ActionParser {
private static final String PARAGRAPH_SPLIT_REGEX = "(?m)(?=^\\s{4})";
private static final IntoParagraphParser paragraphParser = new IntoParagraphParser();
private static final IntoSentenceParser sentenceParser = IntoSentenceParser.getInstance();
private IntoParagraphParser() {
}
public static IntoParagraphParser getInstance() {
return paragraphParser;
}
public ComponentText parse(String text) throws TextException {
ComponentText oneParagraph;
ComponentText componentParagraph = new CompositeText(text, TypeComponent.PARAGRAPH);
String[] arrayParagraph = text.split(PARAGRAPH_SPLIT_REGEX);
for(String element: arrayParagraph) {
oneParagraph = new CompositeText(element, TypeComponent.PARAGRAPH);
oneParagraph.add(sentenceParser.parse(element));
componentParagraph.add(oneParagraph);
}
return componentParagraph;
}
}
Need #Override the method toString() in CompositeText like this:
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (ComponentText component : childComponents) {
builder.append(component.toString());
}
return builder.toString();
}
But how to write this code correctly with Stream API?
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
childComponents.stream().map(...????
return builder.toString();
}

cannot fetch the exact dto returned from ejb to liferay controller

I am doing a liferay project which use ejb at back end. so my ejb method looks like this:-
#Override
public List<RmisPaymentDetailsDto> getEpaymentDetails(String ebpCode) {
Query q = entityManager.createQuery("select s from EpaymentBo s where s.ebpCode=:ebpcode")
.setParameter("ebpcode",ebpCode);
#SuppressWarnings("unchecked")
List<ProductBo> list = q.getResultList();
Iterator<ProductBo> i = list.iterator();
List<RmisPaymentDetailsDto> rList = new ArrayList<RmisPaymentDetailsDto>();
while(i.hasNext()){
EpaymentBo ep =(EpaymentBo) i.next();
RmisPaymentDetailsDto dto = new RmisPaymentDetailsDto();
dto.setAdvertisementcode(ep.getAdvertisementcode());
dto.setAmount(ep.getAmount());
dto.setStudentmasterid(ep.getStudentmasterid());
dto.setEbpgendate(ep.getEbp_gen_date());
dto.setEbpcode(ep.getEbpCode());
dto.setPaymentstatus(ep.getPaymentstatus());
dto.setCandidatenameinnepali(ep.getCandidatenameinnepali());
rList.add(dto);
}
return rList;
}
the above method successfully fetches data from database and sets it to my RmisPaymentDetailsDto.
like this:-
now i am calling same method from my liferay controlller.
PreExaminationRemote preRef = (PreExaminationRemote) jndiContext
.lookup("PreExamination/remote");
List<RmisPaymentDetailsDto> rDto = preRef.getEpaymentDetails(ebpCode);
I am wondering how my one property(candidatenameinnepali) is lost as i return same dto from my ejb.
My dto looks like this:-
public class RmisPaymentDetailsDto implements Serializable {
private static final long serialVersionUID = 1L;
private String advertisementcode;
private String ebpcode;
private String amount;
private String studentmasterid;
private Date ebpgendate;
private String paymentstatus;
private String candidatenameinnepali;
public String getCandidatenameinnepali() {
return candidatenameinnepali;
}
public void setCandidatenameinnepali(String candidatenameinnepali) {
this.candidatenameinnepali = candidatenameinnepali;
}
public String getAdvertisementcode() {
return advertisementcode;
}
public void setAdvertisementcode(String advertisementcode) {
this.advertisementcode = advertisementcode;
}
public String getEbpcode() {
return ebpcode;
}
public void setEbpcode(String ebpcode) {
this.ebpcode = ebpcode;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getStudentmasterid() {
return studentmasterid;
}
public void setStudentmasterid(String studentmasterid) {
this.studentmasterid = studentmasterid;
}
public Date getEbpgendate() {
return ebpgendate;
}
public void setEbpgendate(Date ebpgendate) {
this.ebpgendate = ebpgendate;
}
public String getPaymentstatus() {
return paymentstatus;
}
public void setPaymentstatus(String paymentstatus) {
this.paymentstatus = paymentstatus;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

Exception being thrown by hibernate in specifit request orders

I am experiencing strange behavior. I am using hibernate. I have two tables.
#Entity
public class Nemocnica implements java.io.Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="N_ID")
private BigDecimal NId;
#Column(name="adresa")
private String adresa;
#OneToMany
private Set sanitkas = new HashSet(0);
public Nemocnica() {
}
public Nemocnica( String adresa) {
this.NId = NId;
}
public Nemocnica(BigDecimal NId, String adresa) {
this.NId = NId;
this.adresa = adresa;
}
public Nemocnica(BigDecimal NId, String adresa, Set sanitkas) {
this.NId = NId;
this.adresa = adresa;
this.sanitkas = sanitkas;
}
public BigDecimal getNId() {
return this.NId;
}
public void setNId(BigDecimal NId) {
this.NId = NId;
}
public String getAdresa() {
return this.adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
public Set getSanitkas() {
return this.sanitkas;
}
public void setSanitkas(Set sanitkas) {
this.sanitkas = sanitkas;
}
}
and second
#Entity
public class Sanitka implements java.io.Serializable {
private BigDecimal sanitkaId;
private transient Nemocnica nemocnica;
private BigDecimal kapacita;
#ManyToOne
#JoinColumn(name="nemocnica_n_id")
private Set sanitaris = new HashSet(0);
public Sanitka() {
}
public Sanitka(BigDecimal sanitkaId, Nemocnica nemocnica, BigDecimal kapacita) {
this.sanitkaId = sanitkaId;
this.nemocnica = nemocnica;
this.kapacita = kapacita;
}
public Sanitka(BigDecimal sanitkaId, Nemocnica nemocnica, BigDecimal kapacita, Set sanitaris) {
this.sanitkaId = sanitkaId;
this.nemocnica = nemocnica;
this.kapacita = kapacita;
this.sanitaris = sanitaris;
}
public BigDecimal getSanitkaId() {
return this.sanitkaId;
}
public void setSanitkaId(BigDecimal sanitkaId) {
this.sanitkaId = sanitkaId;
}
#ManyToOne(cascade=CascadeType.ALL)
public Nemocnica getNemocnica() {
return this.nemocnica;
}
public void setNemocnica(Nemocnica nemocnica) {
this.nemocnica = nemocnica;
}
public BigDecimal getKapacita() {
return this.kapacita;
}
public void setKapacita(BigDecimal kapacita) {
this.kapacita = kapacita;
}
public Set getSanitaris() {
return this.sanitaris;
}
public void setSanitaris(Set sanitaris) {
this.sanitaris = sanitaris;
}
}
And routes that mannipulate with them.
nemocnicaRoute:
#Path("nemocnica")
public class nemocnicaRoute {
// private static final helper db = new helper();
#GET
#Path("all")
#Produces(MediaType.APPLICATION_JSON)
public String getName(){
List<Nemocnica> l = db.helper.getNemocnicas();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
//System.out.println( json );
//return l.toString();
return gson.toJson(l);
}
// another methods
}
sanitkaRoute
#Path("sanitka")
public class sanitkaRoute {
//private static final helper db = new helper();
#GET
#Path("all")
#Produces("text/plain")
public String getName(){
List<Sanitka> l = db.helper.getSanitkas();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
//System.out.println( json );
//return l.toString();
return gson.toJson(l);
}
// another methods
}
I am using these two getName() methods to retrieve all data from said tables.
This cause strange behavior , if i invoke get request on nemocnicaRoute first , it works very well as it should.
However when i invoke get requet on sanitkaRoute first , it works but after that when i want to invoke get request on nemocniceRoute it throws
java.lang.UnsupportedOperationException: Attempted to serialize
java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to
register a type adapter?
Which confuses me , bcs this does not happen when i invoke getRequest on nemocnicaRoute first.
How could i fix this strange behavior?
All help appreciated

Android Parcelable JsonArray in Side JsonObject

When i am trying Parce this json data with GSON. I am unable to get JsonArray in side of JsonObject. Below is my code, every suggestion will get appriciated.
JSON DATA FROM SERVER :
{
"GetJobDetails": {
"MaxAmount": 0,
"CreatorId": 1,
"JobImages": [
{
"ImagePath": "http://192.168.1.108:8088/Uploads/6e660c0c-4a2b- 42dc-ad97-82cc3efe87a0.jpg",
"JobImageId": 1
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/ccf1087d-9f7e-4c21-bc61-8aa3fd924e05.jpg",
"JobImageId": 2
},
{
"ImagePath": "http://192.168.1.108:8088/Uploads/4333e8b6-0079-457f-a225-fd7900ea81b1.jpg",
"JobImageId": 3
}
],
}
}
In ACTIVITY :
Gson gson = new Gson();
String response = new String(mresponce);
JobDetails jobDetails= gson.fromJson(response, JobDetails .class);
Log.e("JobDetails ",""+jobDetails.getJobImagesList());
this log prints allways null even when i have images list there in my data.
MODEL CLASS :
public class JobDetails implements Parcelable {
private int MaxAmount;
private int CreatorId;
private List<JobImage> JobImages;
public JobDetails() {
}
public JobDetails(Parcel parcel) {
this.MaxAmount = parcel.readInt();
this.CreatorId= parcel.readInt();
this.JobImages = new ArrayList<JobImage>();
parcel.readTypedList(JobImages, JobImage.CREATOR);
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.MaxAmount);
dest.writeInt(this.CreatorId);
dest.writeList(this.JobImages);
// TODO: Not Parceling AddressList
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public JobDetails createFromParcel(Parcel in) {
return new JobDetails(in);
}
public JobDetails[] newArray(int size) {
return new JobDetails[size];
}
};
public List<JobImage> getJobImagesList() {
return JobImages;
}
public void setJobImagesList(List<JobImage> jobImages) {
JobImages = jobImages;
}
public int getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(int maxAmount) {
MaxAmount= maxAmount;
}
}
ANOTHER MODEL CLASS FOR JOBIMAGE:
public class JobImage implements Parcelable {
private String ImagePath;
private int JobImageId;
JobImage(){
}
public JobImage(Parcel in) {
this.ImagePath = in.readString();
this.JobImageId = in.readInt();
}
// Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.ImagePath);
dest.writeInt(this.JobImageId);
// TODO: Not Parceling AddressList
}
public static final Creator CREATOR = new Creator() {
public JobImage createFromParcel(Parcel in) {
return new JobImage(in);
}
public JobImage[] newArray(int size) {
return new JobImage[size];
}
};
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String imagePath) {
ImagePath = imagePath;
}
public int getJobImageId() {
return JobImageId;
}
public void setJobImageId(int jobImageId) {
JobImageId = jobImageId;
}
}
Please help me to find what i am doing wrong in this :
Your top-level JSON object is not a JobDetails object, it is an object that has JobDetails member name GetJobDetails. You need to handle this level of your JSON. You can do it with a custom TypeAdapter, or perhaps easier, just make a container object and deserialize it.
class JobDetailContainer {
private JobDetails GetJobDetails;
public JobDetails getJobDetails() {
return GetJobDetails;
}
}
then use --
Gson gson = new Gson();
String response = new String(mresponce);
GetJobDetails getJobDetails= gson.fromJson(response, GetJobDetails.class);
Log.e("JobDetails ",""+getJobDetails.getJobDetails().getJobImagesList());
Agreed with #iagreen ...I should handel top level json object too..this is what i have done after doing some R&D
public class GetJobDetails {
public GetJobDetailsResult getGetJobDetailsResult() {
return GetJobDetailsResult;
}
public void setGetJobDetailsResult(GetJobDetailsResult GetJobDetailsResult) {
this.GetJobDetailsResult = GetJobDetailsResult;
}
}
For Inner Json :
public class GetJobDetailsResult {
private Integer MaxAmount;
private Integer CreatorTotJobPosted;
private List<JobImage> JobImages = new ArrayList<JobImage>();
public Integer getMaxAmount() {
return MaxAmount;
}
public void setMaxAmount(Integer MaxAmount) {
this.MaxAmount = MaxAmount;
}
public Integer getCreatorTotJobPosted() {
return CreatorTotJobPosted;
}
public void setCreatorTotJobPosted(Integer CreatorTotJobPosted) {
this.CreatorTotJobPosted = CreatorTotJobPosted;
}
public List<JobImage> getJobImages() {
return JobImages;
}
public void setJobImages(List<JobImage> JobImages) {
this.JobImages = JobImages;
}
}
Finally For To Hold JobImages
public class JobImage {
private String ImagePath;
private Integer JobImageId;
public String getImagePath() {
return ImagePath;
}
public void setImagePath(String ImagePath) {
this.ImagePath = ImagePath;
}
public Integer getJobImageId() {
return JobImageId;
}
public void setJobImageId(Integer JobImageId) {
this.JobImageId = JobImageId;
}
}
Final Step :
Gson gson = new Gson();
String response = new String(jsonObjectresponce.toString());
GetJobDetails getJobDetails = gson.fromJson(response, GetJobDetails.class);
GetJobDetailsResult result = getJobDetails.getGetJobDetailsResult();
// now result object contains my json data.

Loading an ArrayList from another serialized class to use in a ListView

I am still new to Android, I'm primarily an iOS developer.
I don't know why I can't test to see whether or not the ListArray is empty or not. I need to test and use the size of it anyways.
This is declared within the class:
Projects projects = new Projects();
The following code does not like projects.videos.size() being compared nil or 0.
try
{
if (projects != null)
{
int numberOfVideos = projects.videos.size();
if(numberOfVideos==0)
{
// myStringArray = new String[projects.videos.size()];
//
//
//
// for (int i = 0;i < projects.videos.size();i++)
// {
// myStringArray[i] = projects.videos.get(i);
// }
}
else
{
// myStringArray = new String[1];
// myStringArray[0] = "No projects";
}
}
else
{
System.out.println("Sucess");
}
}
catch (Exception e)
{
System.out.println(e);
System.out.println("somethingbad has happened");
System.out.println(projects.videos.size());
}
This is what the projects class looks like:
package com.example.musicvideomaker;
import java.util.ArrayList;
import java.util.UUID;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Projects implements Serializable{
public String projectName;
public String musicStuff;
public String songTitle;
public String guid;
public boolean isBuiltVideo;
public boolean isListOfBuiltVideos;
public int selectedIndex;
public ArrayList<String> videos;
public ArrayList<String> builtVideos;
public ArrayList<Number> tPoints;
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
public void setMusicStuff(String musicStuff)
{
this.musicStuff = musicStuff;
}
public void setSongTitle(String songTitle)
{
this.songTitle = songTitle;
}
public void setGuid()
{
UUID uuid = UUID.randomUUID();
this.guid = uuid.toString();
}
public void isBuiltVideo(boolean isBuiltVideo)
{
this.isBuiltVideo = isBuiltVideo;
}
public void isListOfBuiltVideos(boolean isListOfBuiltVideos)
{
this.isListOfBuiltVideos = isListOfBuiltVideos;
}
public void setSelectedIndex(int selectedIndex)
{
this.selectedIndex = selectedIndex;
}
public void addRecordedVideo(String recordedVideo)
{
this.videos.add(recordedVideo);
}
public void addBuiltVideo(String builtVideo)
{
this.builtVideos.add(builtVideo);
}
public void addTPoint(Number tPoint)
{
this.tPoints.add(tPoint);
}
}
I removed int numberOfVideos = projects.videos.size();
Instead of using if(numberOfVideos==0) I used projects.videos == null
I think it was because my projects are null so it crashes when trying to pull the size of the arrayList.

Categories