JAXB object containment to xml - java

I am trying to print the xml from java using jaxb.
The code I have is as follows:
public class MyXMLGenerator {
public static void main(String[] args) throws Exception {
JAXBPojo jaxbPojo = new JAXBPojo();
jaxbPojo.setName("setName");
jaxbPojo.setId(345);
JAXBContext jc = JAXBContext.newInstance(JAXBPojo.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(jaxbPojo, System.out);
}
}
#XmlRootElement
public class JAXBPojo {
private int id;
private String name;
private Date dob;
#XmlElement(namespace="ddd")
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress() {
address = new Address();
address.setHouseName("setHouseName");
address.setStateName("setStateName");
address.setLocalityName("setLocalityName");
address.setAreaName("setAreaName");
address.setCityName("setCityName");
}
}
#XmlElement
public class Address {
private String houseName;
private String streetName;
private String localityName;
private String areaName;
private String cityName;
private String districtName;
private String stateName;
private String countryName;
public String getHouseName() {
return houseName;
}
public void setHouseName(String houseName) {
this.houseName = houseName;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getLocalityName() {
return localityName;
}
public void setLocalityName(String localityName) {
this.localityName = localityName;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
I get this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxbPojo xmlns:ns2="ddd">
<id>345</id>
<name>setName</name>
</jaxbPojo>
But when I supply value for address class in the main method, I do get the address as well in the output like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxbPojo>
<address>
<areaName>setAreaName</areaName>
<cityName>setCityName</cityName>
<houseName>setHouseName</houseName>
<localityName>setLocalityName</localityName>
<stateName>setStateName</stateName>
</address>
<id>345</id>
<name>setName</name>
</jaxbPojo>
what changes do I have to do to get it working in the current case where I get values for address class in jaxbpojo?
Thanks in advance...

I am not exactly sure what you want but I would change setAddress to:
public void setAddress(Address address) {
this.address = address;
}
main to :
public static void main(String[] args) throws Exception {
JAXBPojo jaxbPojo = new JAXBPojo();
jaxbPojo.setName("setName");
jaxbPojo.setId(345);
Address address = new Address();
address.setHouseName("setHouseName");
address.setStateName("setStateName");
address.setLocalityName("setLocalityName");
address.setAreaName("setAreaName");
address.setCityName("setCityName");
jaxbPojo.setAddress(address);
JAXBContext jc = JAXBContext.newInstance(JAXBPojo.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(jaxbPojo, System.out);
}

Related

Not able to retrive data from Crud Operation in Hibernate

I have a application written in Spring, Hibernate and SpringBoot,
I have 2 entities class with one to many mapping,
Here are my LeadUserDb entity class
#Entity
#Table(name="lead_user_db")
#NamedQuery(name="LeadUserDb.findAll", query="SELECT l FROM LeadUserDb l")
public class LeadUserDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name="branchcode")
private String branchcode;
#Column(name="reporting_level")
private int reportingLevel;
//bi-directional many-to-one association to UserBasicDetailsDb
#ManyToOne
#JoinColumn(name="email_Id")
private UserBasicDetailsDb userBasicDetailsDb;
public LeadUserDb() {
}
public String getBranchcode() {
return this.branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public int getReportingLevel() {
return this.reportingLevel;
}
public void setReportingLevel(int reportingLevel) {
this.reportingLevel = reportingLevel;
}
public UserBasicDetailsDb getUserBasicDetailsDb() {
return this.userBasicDetailsDb;
}
public void setUserBasicDetailsDb(UserBasicDetailsDb userBasicDetailsDb) {
this.userBasicDetailsDb = userBasicDetailsDb;
}
And This is my UserBasicDetailsDb Entity Class
#Entity
#Table(name="user_basic_details_db")
public class UserBasicDetailsDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String email;
private String address;
private String city;
private String dob;
private String mobile;
private String name;
private String pan;
private String pincode;
private String state;
#OneToMany(mappedBy="userBasicDetailsDb")
private List<LeadUserDb> leadUserDbs;
public UserBasicDetailsDb() {
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getDob() {
return this.dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getMobile() {
return this.mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPan() {
return this.pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public List<LeadUserDb> getLeadUserDbs() {
return this.leadUserDbs;
}
public void setLeadUserDbs(List<LeadUserDb> leadUserDbs) {
this.leadUserDbs = leadUserDbs;
}
public LeadUserDb addLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().add(leadUserDb);
leadUserDb.setUserBasicDetailsDb(this);
return leadUserDb;
}
public LeadUserDb removeLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().remove(leadUserDb);
leadUserDb.setUserBasicDetailsDb(null);
return leadUserDb;
}
what i want to achieve is to create a query like this one
SELECT a.branchcode as branchCode,b.name FROM lead_user_db a
inner join user_basic_details_db b
where b.email = a.email_id and a.reporting_level = 3
here is what I have written my Repository class
public interface GetUserList extends CrudRepository<LeadUserDb, Integer> {
#Query(value = "SELECT a.id, a.branchcode as branchCode,b.name as name,a.reporting_level,a.email_id FROM lead_user_db a\n" +
"inner join user_basic_details_db b\n" +
"where b.email = a.email_id and a.reporting_level = ?1", nativeQuery = true)
List<LeadUserDb> findByReportingLevel(int reportingLevel);
}
and this is how I am calling it
UserBasicDetailsDb details = GetUserList.findByReportingLevel(3);
NOTE
Getting a new error Cannot determine value type from string test#dev.com
I am getting a hell lot of data, and the actual output have only 2 records
My question is how can i fetch the list of user based on reportingLevel
Any help would be appreciated

Data integrity when using parallel stream

I have the implemented the below and I have not tested it yet with large amount of data.
public class Main {
public static void main(String[] args) {
CombinedData combinedData = new CombinedData();
List<String> nameList = Arrays.asList("x1", "x3", "x2");
nameList.parallelStream().forEach(name -> {
populateDetails(name, combinedData);
});
}
static void log(String str) {
System.out.println(str);
}
static void populateDetails(String name, CombinedData combinedData) {
if (combinedData.getOrg() == null) {
combinedData.setOrg(MyUtil.getOrg(name));
}
if (combinedData.getRawData() != null) {
combinedData.setRawData(combinedData.getRawData() + name);
}
combinedData.addToDetails(new Details(name, MyUtil.getAdd(name)));
}
}
class CombinedData {
private String org;
private List<Details> details;
private String rawData;
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public void addToDetails(Details details) {
this.details.add(details);
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
public String getRawData() {
return rawData;
}
public void setRawData(String rawData) {
this.rawData = rawData;
}
}
class Details {
private String name;
private String address;
public Details(
String name,
String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
If you check the line 13 and 16 I need to add the org to combined response only once and I have added the check there and also I need to append the name to the rawData. My question is that since I'm using parallel stream how would that behave.
Im sure there might be a scenario that when threads are in parallel thing might break.
How can I go ahead and handle that scenario?

I can't read attributes with namespace (ns2) using JAXB to parse XML in Java

I have to read data from this XML file:
<SENT_112 xmlns:ns2="http://www.mf.gov.pl/SENT/2017/01/18/STypes.xsd" xmlns="http://www.mf.gov.pl/SENT/2017/01/18/SENT_112.xsd">
<Carrier><ns2:TraderInfo><ns2:IdSisc>PL957271726800000</ns2:IdSisc><ns2:TraderName>FIRMA SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ</ns2:TraderName>
<ns2:TraderIdentityType>NIP</ns2:TraderIdentityType>
<ns2:TraderIdentityNumber>9572717268</ns2:TraderIdentityNumber>
</ns2:TraderInfo>
<ns2:TraderAddress><ns2:Street>Arysztacka</ns2:Street><ns2:HouseNumber>91A</ns2:HouseNumber><ns2:City>Cieszyn</ns2:City><ns2:Country>PL</ns2:Country><ns2:PostalCode>43-400</ns2:PostalCode></ns2:TraderAddress></Carrier>
</SENT_112>
My main class is using JAXB:
JAXBContext jc = JAXBContext.newInstance(SENT_112.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
SENT_112 sent_112 = (SENT_112) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(sent_112, System.out);
Carrier.java
public class Carrier implements java.io.Serializable {
private int nrCarrier;
//private String sentnumber;
private String IdSisc;
private String tradername;
private String traderidentitytype;
private String traderidentitynumber;
private String street;
private String housenumber;
private String city;
private String country;
private String postalcode;
//Contrutors
//Getters and Setters
//ToString Method
SENT_112.java
#XmlRootElement(name="SENT_112")
public class SENT_112 {
#XmlElement(name="Carrier")
private List<Carrier> carrier;
public List<Carrier> getCarrier() {
return carrier;
}
PACKAGE-INFO.JAVA
#XmlSchema(
namespace = "http://www.mf.gov.pl/SENT/2017/01/18/SENT_112.xsd",
elementFormDefault = XmlNsForm.QUALIFIED)
package com.przedlak.entity;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
And my Code return that
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SENT_112 xmlns="http://www.mf.gov.pl/SENT/2017/01/18/SENT_112.xsd">
<Carrier>
<nrCarrier>0</nrCarrier>
</Carrier>
</SENT_112>
What is wrong with my Code? I need read all information.
If you want to get all information, write your classes appropriately i.e. to retrieve all data. Change Carrier.java to :
Carrier.java
#XmlRootElement(name="Carrier")
#XmlAccessorType(XmlAccessType.FIELD)
public class Carrier implements java.io.Serializable
{
#XmlElement( name = "TraderInfo" )
private TraderInfo traderInfo;
#XmlElement( name = "TraderAddress" )
private TraderAddress traderAddress;
private int nrCarrier;
public int getNrCarrier() {
return nrCarrier;
}
public void setNrCarrier(int nrCarrier) {
this.nrCarrier = nrCarrier;
}
public TraderInfo getTraderInfo() {
return traderInfo;
}
public void setTraderInfo(TraderInfo traderInfo) {
this.traderInfo = traderInfo;
}
public TraderAddress getTraderAddress() {
return traderAddress;
}
public void setTraderAddress(TraderAddress traderAddress) {
this.traderAddress = traderAddress;
}
}
Then define two classes for TraderAddress, TraderInfo as:
TraderInfo
#XmlRootElement(name="TraderInfo")
#XmlAccessorType(XmlAccessType.FIELD)
public class TraderInfo
{
#XmlElement( name = "IdSisc")
private String IdSisc;
#XmlElement( name = "TraderName")
private String tradername;
#XmlElement( name = "TraderIdentityType")
private String traderidentitytype;
#XmlElement( name = "TraderIdentityNumber")
private String traderidentitynumber;
public String getIdSisc() {
return IdSisc;
}
public void setIdSisc(String idSisc) {
IdSisc = idSisc;
}
public String getTradername() {
return tradername;
}
public void setTradername(String tradername) {
this.tradername = tradername;
}
public String getTraderidentitytype() {
return traderidentitytype;
}
public void setTraderidentitytype(String traderidentitytype) {
this.traderidentitytype = traderidentitytype;
}
public String getTraderidentitynumber() {
return traderidentitynumber;
}
public void setTraderidentitynumber(String traderidentitynumber) {
this.traderidentitynumber = traderidentitynumber;
}
}
TraderAddress.java
#XmlRootElement(name="TraderInfo")
#XmlAccessorType(XmlAccessType.FIELD)
public class TraderAddress
{
#XmlElement( name = "Street")
private String street;
#XmlElement( name = "HouseNumber")
private String houseNumber;
#XmlElement( name = "City")
private String city;
#XmlElement( name = "Country")
private String country;
#XmlElement( name = "PostalCode")
private String postalCode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
}
With this setup, you should get full xml from marshalling:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SENT_112 xmlns="http://www.mf.gov.pl/SENT/2017/01/18/SENT_112.xsd">
<Carrier>
<TraderInfo>
<IdSisc>PL957271726800000</IdSisc>
<TraderName>FIRMA SPÓÅ?KA Z OGRANICZONÄ„ ODPOWIEDZIALNOÅšCIÄ„
</TraderName>
<TraderIdentityType>NIP</TraderIdentityType>
<TraderIdentityNumber>9572717268</TraderIdentityNumber>
</TraderInfo>
<TraderAddress>
<Street>Arysztacka</Street>
<HouseNumber>91A</HouseNumber>
<City>Cieszyn</City>
<Country>PL</Country>
<PostalCode>43-400</PostalCode>
</TraderAddress>
<nrCarrier>0</nrCarrier>
</Carrier>
</SENT_112>

ObjectMapper can't map the variables of inner class

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

Gson, parsing json innerclass list, javabean

Well so I'm trying to parse a bit of JSon. I succeeded to parse:
Member.json:
{"member":{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"peter#adress.com "}}
but what if I need to parse:
{"Members":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":‌​‌​"peter#adress.com"},{"id":645231,"name":"Bill","profileIconId":123,"age":56,"em‌​ai‌​l":"bill#adress.com"}]}
Ofcourse I searched the web, I think, I need to use "List<>" here private List<memberProfile> member;but how do I "get" this from my main class??
I used this to parse the first string:
memeberClass.java
public class memberClass {
private memberProfile member;
public memberProfile getMember() {
return member;
}
public class memberProfile{
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
}
memberToJava.java
public class memberToJava {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader("...Member.json"));
//convert the json string back to object
memberClass memberObj = gson.fromJson(br, memberClass.class);
System.out.println("Id: " + memberObj.getMember().getId());
System.out.println("Namw: " + memberObj.getMember().getName());
System.out.println("ProfileIconId: " + memberObj.getMember().getProfileIconId());
System.out.println("Age: " + memberObj.getMember().getAge());
System.out.println("Email: " + memberObj.getMember().getEmail());
} catch (IOException e) {
e.printStackTrace();
}
}
}
see below code
MemberClass.java
import java.util.List;
public class MemberClass {
private List<MemberProfile> member;
public List<MemberProfile> getMember() {
return member;
}
public void setMember(List<MemberProfile> member) {
this.member = member;
}
public class MemberProfile {
int id;
String name;
int profileIconId;
int age;
String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProfileIconId() {
return profileIconId;
}
public void setProfileIconId(int profileIconId) {
this.profileIconId = profileIconId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
}
Main Class
import com.google.gson.Gson;
public class MemTest {
public static void main(String[] args) {
String json = "{'member':[{'id':585897,'name':'PhPeter','profileIconId':691,'age':99,'email':‌​‌​'peter#adress.com'},{'id':645231,'name':'Bill','profileIconId':123,'age':56,'em‌​ai‌​l':'bill#adress.com'}]}";
MemberClass memberClass = new Gson().fromJson(json, MemberClass.class);
System.out.println(new Gson().toJson(memberClass));
}
}
Output
{"member":[{"id":585897,"name":"PhPeter","profileIconId":691,"age":99,"email":"‌​‌​\u0027peter#adress.com\u0027"},{"id":645231,"name":"Bill","profileIconId":123,"age":56}]}
Hi I made some changes to your application and it seems to work now ! You where quite close alls you need is a wrapper for the array.
public class memberWrapper {
private List<memberClass> Members;
public List<memberClass> getMembers() {
return Members;
}
public void setMembers(List<memberClass> members) {
this.Members = members;
}
}
Then I changed youir original class a little:
public class memberClass {
int id;
String name;
int profileIconId;
int age;
String email;
//Getter
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getProfileIconId() {
return profileIconId;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
and then in the main:
BufferedReader br = new BufferedReader(new FileReader("stuff.json"));
//convert the json string back to object
memberWrapper memberObj = gson.fromJson(br, memberWrapper.class);
System.out.println("Id: " + memberObj.getMembers().get(0).getId());
It should work now the important thing when dealing with JSOn is to just make sure the key matches the name of your variables.

Categories

Resources