I am getting JSON String data like
{"username":"KU","password":"KU"}.
How to convert this string to JAXBElement object.
Please give me answer.
You can use Jackson to unmarshal JSON easily. See the code below for your username and password case above. It outputs the following to the console console showing it has created an instance of the class from the JSON string.
{"username":"KU","password":"KU"} -> Username [KU], Password [KU].
import org.codehaus.jackson.map.ObjectMapper;
public class JaxbTest {
public static void main(String[] args) throws Throwable {
String json = "{\"username\":\"KU\",\"password\":\"KU\"}";
ObjectMapper mapper = new ObjectMapper();
JavaObject javaObject = mapper.readValue(json, JavaObject.class);
System.out.println(json + " -> " + javaObject.toString());
}
private static class JavaObject {
private String username;
private String password;
public JavaObject() { }
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "Username [" + this.username + "], Password [" + this.password + "]";
}
}
}
Related
I am trying to experiment and learn BuilderPattern,reading from json file at the same time. My goal is to create object using the data I get from the json file. This is how the json file looks like:
[{
"firstName": "Git",
"lastName": "Hub",
"website": "howtodoinjava.com"
},
{
"firstName": "Brian",
"lastName": "Schultz"
}
]
Class1: Employee Class
public class Employee {
private String firstName; // required
private String lastName; // required
private String website; // optional
//Only has setters
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setWebsite(String website) {
this.website = website;
}
//no public constructor. So the only way to get a Employee object is through the EmployeeBuilder class.
private Employee(EmployeeBuilder builder) {
this.firstName = firstName;
this.lastName = lastName;
this.website = website;
}
public static class EmployeeBuilder {
private String firstName; // required
private String lastName; // required
private String website; // optional
public EmployeeBuilder() throws IOException {
}
public EmployeeBuilder requiredFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public EmployeeBuilder requiredLastName(String lastName) {
this.lastName = lastName;
return this;
}
public EmployeeBuilder optionalWebsite(String website) {
this.website = website;
return this;
}
//Return the finally constructed User object
public Employee build() {
Employee emp = new Employee(this);
return emp;
}
}
}
Class2: User Class
public class User {
String firstName;
String lastName;
String website;
//Using Getters to get values from Json
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getWebsite() {
return website;
}
}
3 Main class
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper object = new ObjectMapper();
User[] user = object.readValue(new File("C:\\MyTemp\\jackson.json"), User[].class);
//Employee employee= new Employee.EmployeeBuilder().requiredFirstName(person.getFirstName()).requiredLastName(person.getLastName()).optionalWebsite(person.getWebsite()).build();
List<User> emp1 = object.readValue("C:\\MyTemp\\jackson.json", new TypeReference<List<User>>() {});
emp1.stream().forEach(x -> System.out.println(x));
/*for (User person : user) {
Employee employee= new Employee.EmployeeBuilder().requiredFirstName(person.getFirstName()).build();
System.out.println(employee);
} */
}
}
Problem: When I run this code all I get are the 1st names. Git and Brian. I am not getting the last names or website.
Can someone please suggest what am I missing? Thanks in advance for your time.
i was try to build real time car rent but i got this error returning null of datasnapshot and tried all fix thats impossible without any success
i don't know where is a problem and why my database dosn't response the request
DatabaseReference driverLocation = FirebaseDatabase.getInstance().getReference(Common.driver_location_tbl);
GeoFire gf = new GeoFire(driverLocation);
GeoQuery geoQuery = gf.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),distance);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(final String key, final GeoLocation location) {
FirebaseDatabase.getInstance().getReference(Common.driver_tbl)
.child(key)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Rider rider = dataSnapshot.getValue(Rider.class);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.latitude,location.longitude))
.flat(true)
.title("Driver Name :"+rider.getUsername())
.snippet("Phone : "+rider.getPhone())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.cars)));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and my Rider class
public class Rider {
private String email,password,phone,username;
public Rider() {
}
public Rider(String email, String password, String phone, String username) {
this.email = email;
this.password = password;
this.phone = phone;
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
How to fix app crach and returning null of datasnapshot ?
I have research for a fix and have not found anything.
ok i fixed it
problem was i register users with name not Uid so when i request name and phone got n
long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>
Json response with api URLhttp://192.168.0.19:2000/api/userprofile?phone=0722931069&Password=1111
{
"Username":"abel",
"ProfileId":"746737",
"Password":"1111",
"SaccaUssdId":"3728282",
"PaybillNo":"74883",
"Phonenumber":"0722931069",
"CustomerType":"d",
"RegistrationDate":"2005-12-09T00:00:00",
"TimeStamp":"2005-12-09T00:00:00",
"PreferredModeOfComm":"phonecall",
"APIURL":"hhh",
"APIUsername":"kplDL",
"APIPassword":"JKSDjic"
}
Here is my POJO class, PLease help sort out this issue
public class Fetchnumber {
private String Username;
private String ProfileId;
private String Password;
private String SaccaUssdId;
private String PaybillNo;
private String Phonenumber;
private String CustomerType;
private String RegistrationDate;
private String TimeStamp;
private String PreferredModeOfComm;
private String APIURL;
private String APIUsername;
private String APIPassword;
public Fetchnumber(String username, String profileId, String password, String saccaUssdId, String paybillNo, String phonenumber, String customerType, String registrationDate, String timeStamp, String preferredModeOfComm, String APIURL, String APIUsername, String APIPassword) {
this.Username = username;
this.ProfileId = profileId;
this.Password = password;
this.SaccaUssdId = saccaUssdId;
this.PaybillNo = paybillNo;
this.Phonenumber = phonenumber;
this.CustomerType = customerType;
this.RegistrationDate = registrationDate;
this.TimeStamp = timeStamp;
this.PreferredModeOfComm = preferredModeOfComm;
this.APIURL = APIURL;
this.APIUsername = APIUsername;
this.APIPassword = APIPassword;
}
public String getUsername() {
return Username;
}
public String getProfileId() {
return ProfileId;
}
public String getPassword() {
return Password;
}
public String getSaccaUssdId() {
return SaccaUssdId;
}
public String getPaybillNo() {
return PaybillNo;
}
public String getPhonenumber() {
return Phonenumber;
}
public String getCustomerType() {
return CustomerType;
}
public String getRegistrationDate() {
return RegistrationDate;
}
public String getTimeStamp() {
return TimeStamp;
}
public String getPreferredModeOfComm() {
return PreferredModeOfComm;
}
public String getAPIURL() {
return APIURL;
}
public String getAPIUsername() {
return APIUsername;
}
public String getAPIPassword() {
return APIPassword;
}
}
`Please help me, I am using retrofit2 library and Pinview and mobile number to authenticate users but as soon as I finish keying in pin, the app listens to pin key in.
Here is how I have declared base url and method that takes two parameters to be queried
String BASE_URL="http://192.168.0.19:2000/";
#GET("api/userprofile")
Call<Fetchnumber> getNumbers(#Query("phone" ) String phone, #Query("Password") String Password);
Here is the error I get in Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String e.uzer.msacco.Fetchnumber.getPassword()' on a null object reference
at e.uzer.msacco.UserLogin$1$1.onDataEntered(UserLogin.java:49)
at com.goodiebag.pinview.Pinview.onTextChanged(Pinview.java:406)
at android.widget.TextView.sendOnTextChanged(TextView.java:8320)
at android.widget.TextView.handleTextChanged(TextView.java:8385)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:10531)
Here is The retrofit library that shows how i have passed two parameters to the method getnumbers
Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
Api api = retrofit.create(Api.class);
Call<Fetchnumber> call = api.getNumbers(phonenumbersubmission.phone_number.getText().toString(),pinview.getValue().toString().trim());
call.enqueue(new Callback<Fetchnumber>() {
Here is how i have handled Onresponse
public void onResponse(Call<Fetchnumber> call, final Response<Fetchnumber> response) {
pinview.setPinViewEventListener(new Pinview.PinViewEventListener() {
#Override
public void onDataEntered(Pinview pinview, boolean b) {
if ((response.body().getPassword().equals(pinview.getValue().toString())&&( response.body().getPhonenumber().toString().equals(phonenumbersubmission.phone_number.toString())))) {
Toast.makeText(UserLogin.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(UserLogin.this, enrollment.class);
startActivity(intent);
} else {
Toast.makeText(UserLogin.this, "Wrong PIN", Toast.LENGTH_LONG).show();
Where getPassword and getPhonenumber() are from POJO class.
Any help will be much appreciated,
Thank you in andvance.
Add #SerializedName annotation to all the fields in your pojo class with respective key names from your json response. it should be like
public class Example {
#SerializedName("Username")
#Expose
private String username;
#SerializedName("ProfileId")
#Expose
private String profileId;
#SerializedName("Password")
#Expose
private String password;
#SerializedName("SaccaUssdId")
#Expose
private String saccaUssdId;
#SerializedName("PaybillNo")
#Expose
private String paybillNo;
#SerializedName("Phonenumber")
#Expose
private String phonenumber;
#SerializedName("CustomerType")
#Expose
private String customerType;
#SerializedName("RegistrationDate")
#Expose
private String registrationDate;
#SerializedName("TimeStamp")
#Expose
private String timeStamp;
#SerializedName("PreferredModeOfComm")
#Expose
private String preferredModeOfComm;
#SerializedName("APIURL")
#Expose
private String aPIURL;
#SerializedName("APIUsername")
#Expose
private String aPIUsername;
#SerializedName("APIPassword")
#Expose
private String aPIPassword;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSaccaUssdId() {
return saccaUssdId;
}
public void setSaccaUssdId(String saccaUssdId) {
this.saccaUssdId = saccaUssdId;
}
public String getPaybillNo() {
return paybillNo;
}
public void setPaybillNo(String paybillNo) {
this.paybillNo = paybillNo;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public String getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(String registrationDate) {
this.registrationDate = registrationDate;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getPreferredModeOfComm() {
return preferredModeOfComm;
}
public void setPreferredModeOfComm(String preferredModeOfComm) {
this.preferredModeOfComm = preferredModeOfComm;
}
public String getAPIURL() {
return aPIURL;
}
public void setAPIURL(String aPIURL) {
this.aPIURL = aPIURL;
}
public String getAPIUsername() {
return aPIUsername;
}
public void setAPIUsername(String aPIUsername) {
this.aPIUsername = aPIUsername;
}
public String getAPIPassword() {
return aPIPassword;
}
public void setAPIPassword(String aPIPassword) {
this.aPIPassword = aPIPassword;
}
}
I have XML as follows
<request type="1">
<request-header/>
<request-details>
<!-- Some more tags -->
</request-details>
</request>
For mapping this XML I have class structure as follows :
public class Request1
{
private RequestDetail_1;
//other members
}
public class Request2
{
private RequestDetail_2;
//other members
}
public class RequestDetail_1
{
//members
}
public class RequestDetail_2
{
//Members
}
What I want to do is ... If attribute type is 1 then I need to create object of type Request_1 , if type is 2 then object type will be Request_2 and so on.
I have gone through this link for reference but still couldn't figure out a way to do this. I want to use pure JAXB and not MOXY or any other such frame works... :( .
Partial code :
#XmlJavaTypeAdapter(RequestAdaptor.class)
#XmlRootElement(name="request")
public class AuthRequest extends Request
{
private AuthRequestDetails requestDetails;
public RequestDetails getRequestDetails()
{
return requestDetails;
}
#Override
public void setRequestDetails(RequestDetails requestDetails)
{
this.requestDetails = (AuthRequestDetails)requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class AuthRequestDetails extends RequestDetails
{
#XmlElement(name="user-name")
private String userName;
#XmlElement(name="password")
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapter(RequestAdaptor.class)
public abstract class Request
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
protected RequestHeader requestHeader;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public abstract void setRequestDetails(RequestDetails requestDetails);
public abstract RequestDetails getRequestDetails();
}
public class RequestAdaptor extends XmlAdapter<RequestDTO, Request>
{
#Override
public RequestDTO marshal(Request v) throws Exception
{
System.out.println("marshal");
RequestDTO lRequestDTO= new RequestDTO();
lRequestDTO.setRequestHeader(v.getRequestHeader());
lRequestDTO.setType(v.getType());
if(v.getType().equals("5"))
{
AuthRequest lRequest = (AuthRequest)v;
}
else
{
PingRequest lRequest = (PingRequest)v;
}
return lRequestDTO;
}
#Override
public Request unmarshal(RequestDTO v) throws Exception
{
System.out.println("unmarshal");
if(v.getType().equals("5"))
{
AuthRequest lRequest = new AuthRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
else
{
PingRequest lRequest = new PingRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestDTO
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
private RequestHeader requestHeader;
#XmlElement(name="request-details")
private RequestDetails requestDetails;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RequestDetails getRequestDetails() {
return requestDetails;
}
public void setRequestDetails(RequestDetails requestDetails) {
this.requestDetails = requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestHeader
{
#XmlElement(name="name")
String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
First thing is : Marshal and Unmarshal of Adaptor is not getting called. I am stuck at this point.
You can use a StAX XmlStreamReader to parse the XML. Then advance it to the root element. When it's at the root element event check the value of the type attribute. Use this value to determine which Class you should pass to the unmarshal method that takes a Class and XmlStreamReader to get the result you are looking for.