Consuming Rest Service - java

I just started with rest services and i have read this https://spring.io/guides/gs/consuming-rest/. Then according to this tutorial i have a service to consume and display.
The service is a rest api and i get a json like that
{
"disclaimer": "1",
"license": "2",
"timestamp": 1458057661,
"base": "someValue",
"rates": {
"one": 3.673019,
"two": 68.449999,
"three": 124.168,
"four": 488.669996,
...,
...,
...
}
}
Then i have created 2 Java class like that
#JsonIgnoreProperties(ignoreUnknown = true)
public class Cur {
private String disclaimer;
private String license;
private String timestamp;
private String base;
private Rates rates;
public Cur() {
super();
}
///get/set
///tostring
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class Rates {
public Rates(){
//// i am not sure here how should i get the rates value.
}
}
the problem is how do i fill the Rates class to get the data into variables so that later i can present the on view.
I use RestTemplate. Here is the test.It works but i have no rates value.
I think i need a Map because rates it's a collection.Any idea how to implement it.
#Test
public void getCurTest() {
String URL="some url";
String JSONTYPE="some json type";
String API="some id";
RestTemplate restTemplate = new RestTemplate();
Cur cur= restTemplate.getForObject(URL+JSONTYPE+API, Cur.class);
log.info("cur");
System.out.println(cur);
}

I had the same some years ago it's a little weird. Here what you can do.
First solution
The simple way is
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("your rest service api");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
String responseValue = EntityUtils.toString(entity);
System.out.println(responseValue);
} else {
// log error
}
} finally {
response.close();
}
}
you can then get everything as a String and with regex parse it and get what you want.
Second solution
you can save all your rest to a database as it is. Use mongodb for faster.
Then you can get it form there to a class and use it.
Third solution
use this tool http://www.jsonschema2pojo.org/ just paste your json and it will create your java classes to use them. You can choose what ever you want to add. This will create your classes then you can use them.
Here for your convenience.
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"disclaimer",
"license",
"timestamp",
"base",
"rates"
})
public class Example {
#JsonProperty("disclaimer")
private String disclaimer;
#JsonProperty("license")
private String license;
#JsonProperty("timestamp")
private Integer timestamp;
#JsonProperty("base")
private String base;
#JsonProperty("rates")
private Rates rates;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Example() {
}
/**
*
* #param timestamp
* #param disclaimer
* #param base
* #param rates
* #param license
*/
public Example(String disclaimer, String license, Integer timestamp, String base, Rates rates) {
this.disclaimer = disclaimer;
this.license = license;
this.timestamp = timestamp;
this.base = base;
this.rates = rates;
}
/**
*
* #return
* The disclaimer
*/
#JsonProperty("disclaimer")
public String getDisclaimer() {
return disclaimer;
}
/**
*
* #param disclaimer
* The disclaimer
*/
#JsonProperty("disclaimer")
public void setDisclaimer(String disclaimer) {
this.disclaimer = disclaimer;
}
/**
*
* #return
* The license
*/
#JsonProperty("license")
public String getLicense() {
return license;
}
/**
*
* #param license
* The license
*/
#JsonProperty("license")
public void setLicense(String license) {
this.license = license;
}
/**
*
* #return
* The timestamp
*/
#JsonProperty("timestamp")
public Integer getTimestamp() {
return timestamp;
}
/**
*
* #param timestamp
* The timestamp
*/
#JsonProperty("timestamp")
public void setTimestamp(Integer timestamp) {
this.timestamp = timestamp;
}
/**
*
* #return
* The base
*/
#JsonProperty("base")
public String getBase() {
return base;
}
/**
*
* #param base
* The base
*/
#JsonProperty("base")
public void setBase(String base) {
this.base = base;
}
/**
*
* #return
* The rates
*/
#JsonProperty("rates")
public Rates getRates() {
return rates;
}
/**
*
* #param rates
* The rates
*/
#JsonProperty("rates")
public void setRates(Rates rates) {
this.rates = rates;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
package com.example;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"one",
"two",
"three",
"four"
})
public class Rates {
#JsonProperty("one")
private Double one;
#JsonProperty("two")
private Double two;
#JsonProperty("three")
private Double three;
#JsonProperty("four")
private Double four;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Rates() {
}
/**
*
* #param two
* #param one
* #param three
* #param four
*/
public Rates(Double one, Double two, Double three, Double four) {
this.one = one;
this.two = two;
this.three = three;
this.four = four;
}
/**
*
* #return
* The one
*/
#JsonProperty("one")
public Double getOne() {
return one;
}
/**
*
* #param one
* The one
*/
#JsonProperty("one")
public void setOne(Double one) {
this.one = one;
}
/**
*
* #return
* The two
*/
#JsonProperty("two")
public Double getTwo() {
return two;
}
/**
*
* #param two
* The two
*/
#JsonProperty("two")
public void setTwo(Double two) {
this.two = two;
}
/**
*
* #return
* The three
*/
#JsonProperty("three")
public Double getThree() {
return three;
}
/**
*
* #param three
* The three
*/
#JsonProperty("three")
public void setThree(Double three) {
this.three = three;
}
/**
*
* #return
* The four
*/
#JsonProperty("four")
public Double getFour() {
return four;
}
/**
*
* #param four
* The four
*/
#JsonProperty("four")
public void setFour(Double four) {
this.four = four;
}
#Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Then you can use it as you want.
I hope all this helps. Take care.

The way your JSON is, to get the Rates populed your class should look like this.
public class Cur {
private String disclaimer;
private String license;
private Integer timestamp;
private String base;
private Rates rates;
}
public class Rates {
private Double one;
private Double two;
private Double three;
private Double four;
//This would be better but the JSON dosnt fit this
//private Map<String, Double> rates;
}
Which API are you triyng to use?

Related

XML to Object mapping

Having hard time to map..
Calling rest and rest return response in XML format..
Help with class mapping in Java Object (method)
<aname>
<bname>
<c id="2">
<cname call="yes" text="no" email="yes"/>
<acc>
<accinfo name="ax" addr="USA"/>
</acc>
</c>
</bname>
</aname>
how can i convert above xml in Java class?
Thank You!
I share solution:
If you use need dependency
<!-- Jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
First class.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "bname" })
#XmlRootElement(name = "aname")
public class Aname {
#XmlElement(required = true)
protected Aname.Bname bname;
/**
* Gets the value of the bname property.
*
* #return possible object is {#link Aname.Bname }
*
*/
public Aname.Bname getBname() {
return bname;
}
/**
* Sets the value of the bname property.
*
* #param value allowed object is {#link Aname.Bname }
*
*/
public void setBname(Aname.Bname value) {
this.bname = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "c" })
public static class Bname {
#XmlElement(required = true)
protected Aname.Bname.C c;
/**
* Gets the value of the c property.
*
* #return possible object is {#link Aname.Bname.C }
*
*/
public Aname.Bname.C getC() {
return c;
}
/**
* Sets the value of the c property.
*
* #param value allowed object is {#link Aname.Bname.C }
*
*/
public void setC(Aname.Bname.C value) {
this.c = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "cname", "acc" })
public static class C {
#XmlElement(required = true)
protected Aname.Bname.C.Cname cname;
#XmlElement(required = true)
protected Aname.Bname.C.Acc acc;
#XmlAttribute(name = "id", required = true)
#XmlSchemaType(name = "unsignedByte")
protected short id;
/**
* Gets the value of the cname property.
*
* #return possible object is {#link Aname.Bname.C.Cname }
*
*/
public Aname.Bname.C.Cname getCname() {
return cname;
}
/**
* Sets the value of the cname property.
*
* #param value allowed object is {#link Aname.Bname.C.Cname }
*
*/
public void setCname(Aname.Bname.C.Cname value) {
this.cname = value;
}
/**
* Gets the value of the acc property.
*
* #return possible object is {#link Aname.Bname.C.Acc }
*
*/
public Aname.Bname.C.Acc getAcc() {
return acc;
}
/**
* Sets the value of the acc property.
*
* #param value allowed object is {#link Aname.Bname.C.Acc }
*
*/
public void setAcc(Aname.Bname.C.Acc value) {
this.acc = value;
}
/**
* Gets the value of the id property.
*
*/
public short getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(short value) {
this.id = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "accinfo" })
public static class Acc {
#XmlElement(required = true)
protected Aname.Bname.C.Acc.Accinfo accinfo;
/**
* Gets the value of the accinfo property.
*
* #return possible object is {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public Aname.Bname.C.Acc.Accinfo getAccinfo() {
return accinfo;
}
/**
* Sets the value of the accinfo property.
*
* #param value allowed object is {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public void setAccinfo(Aname.Bname.C.Acc.Accinfo value) {
this.accinfo = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
public static class Accinfo {
#XmlAttribute(name = "name", required = true)
protected String name;
#XmlAttribute(name = "addr", required = true)
protected String addr;
/**
* Gets the value of the name property.
*
* #return possible object is {#link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* #param value allowed object is {#link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the addr property.
*
* #return possible object is {#link String }
*
*/
public String getAddr() {
return addr;
}
/**
* Sets the value of the addr property.
*
* #param value allowed object is {#link String }
*
*/
public void setAddr(String value) {
this.addr = value;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
public static class Cname {
#XmlAttribute(name = "call", required = true)
protected String call;
#XmlAttribute(name = "text", required = true)
protected String text;
#XmlAttribute(name = "email", required = true)
protected String email;
/**
* Gets the value of the call property.
*
* #return possible object is {#link String }
*
*/
public String getCall() {
return call;
}
/**
* Sets the value of the call property.
*
* #param value allowed object is {#link String }
*
*/
public void setCall(String value) {
this.call = value;
}
/**
* Gets the value of the text property.
*
* #return possible object is {#link String }
*
*/
public String getText() {
return text;
}
/**
* Sets the value of the text property.
*
* #param value allowed object is {#link String }
*
*/
public void setText(String value) {
this.text = value;
}
/**
* Gets the value of the email property.
*
* #return possible object is {#link String }
*
*/
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* #param value allowed object is {#link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
}
}
}
}
Second class.
import javax.xml.bind.annotation.XmlRegistry;
#XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema
* derived classes for package: generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {#link Aname }
*
*/
public Aname createAname() {
return new Aname();
}
/**
* Create an instance of {#link Aname.Bname }
*
*/
public Aname.Bname createAnameBname() {
return new Aname.Bname();
}
/**
* Create an instance of {#link Aname.Bname.C }
*
*/
public Aname.Bname.C createAnameBnameC() {
return new Aname.Bname.C();
}
/**
* Create an instance of {#link Aname.Bname.C.Acc }
*
*/
public Aname.Bname.C.Acc createAnameBnameCAcc() {
return new Aname.Bname.C.Acc();
}
/**
* Create an instance of {#link Aname.Bname.C.Cname }
*
*/
public Aname.Bname.C.Cname createAnameBnameCCname() {
return new Aname.Bname.C.Cname();
}
/**
* Create an instance of {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public Aname.Bname.C.Acc.Accinfo createAnameBnameCAccAccinfo() {
return new Aname.Bname.C.Acc.Accinfo();
}
}
And Main class.
import java.io.StringReader;
import java.text.ParseException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
static ObjectMapper mapper = new ObjectMapper();
public static void main(String... strings) throws ParseException {
String xml = "<aname> <bname> <c id=\"2\"> <cname call=\"yes\" text=\"no\" email=\"yes\"/> <acc> <accinfo name=\"ax\" addr=\"USA\"/> </acc> </c> </bname> </aname>";
Aname clazz = convertXMLToObject(Aname.class, xml);
try {
System.out.println(mapper.writeValueAsString(clazz));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public static <T> T convertXMLToObject(Class<T> clazz, String xml)
{
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
return (T) um.unmarshal(new StringReader(xml));
}
catch (JAXBException je){
throw new RuntimeException(String.format("Exception while Unmarshaller: %s", je.getMessage()));
}
}
}
result this.
{"bname":{"c":{"cname":{"call":"yes","text":"no","email":"yes"},"acc":{"accinfo":{"name":"ax","addr":"USA"}},"id":2}}}

passing custom object in retrofit2

i am trying to pass a custom object via retrofit2, and my question is that does the server writes my custom object to json automatically or do i have to write a php file for that. In the meanwhile I am posting successfully to the server but unable to write to json.
My aim is to write custom object to server, and write the contents of custom objects to json file.
Here is my Retrofit Api
public interface ApsaraCatalogAPI {
#GET("/apsaratrendz/data/apsara_json_document_v2.json")
Call<List<ApsaraCatalogModel>> getFeed();
#POST("/apsaratrendz/data/apsara_json_orders_document.json")
Call<Void> setOrder(#Body OrderModel orderModel);
}
Here is my calling api function
#Override
public void onClick(View v) {
int total = 0;
if(v.getId()==R.id.fabButtonCart && cartlist.size()!=0)
{
// get details from shared preferences
OrderModel orderModel = new OrderModel();
orderModel.setDate(getDate());
orderModel.setName("ssdfs");
orderModel.setEmail("sdf#gmail.com");
orderModel.setNoofitems(String.valueOf(cartlist.size()));
orderModel.setOrderno("32335");
orderModel.setPhone("9896566444");
for(int i=0; i<cartlist.size();i++){
Productdetail pd = new Productdetail();
pd.getSellingprice(String.valueOf(cartlist.get(i).getSellingPrice()));
pd.getPid(cartlist.get(i).getEANCode());
total += cartlist.get(i).getSellingPrice();
orderModel.getProductdetails().add(pd);
}
//
// now go for insertion using retrofit
requestData(orderModel);
Toast.makeText(getApplicationContext(), "Total Price : Rs."+total+"/-", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Cart is Empty", Toast.LENGTH_LONG).show();
}
}
And here is my service request for retrofit api, I am passing the newly created POJO OrderModel class.
private void requestData(OrderModel orderModel) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApsaraCatalogAPI service = retrofit.create(ApsaraCatalogAPI.class);
Call<Void> call = service.setOrder(orderModel);
call.enqueue(new Callback<Void>() {
#Override
public void onResponse(Call<Void> call, Response<Void> response) {
if(response.isSuccessful()){
Log.d("InApi","Yipppie");
}
}
#Override
public void onFailure(Call<Void> call, Throwable t) {
Log.d("InApi","Kaboom");
}
});
}
My POJO Class is given below:
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class OrderModel {
private String name;
private String email;
private String phone;
private String orderno;
private String date;
private String noofitems;
private List<Productdetail> productdetails = new ArrayList<Productdetail>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* #param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* #return
* The phone
*/
public String getPhone() {
return phone;
}
/**
*
* #param phone
* The phone
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
*
* #return
* The orderno
*/
public String getOrderno() {
return orderno;
}
/**
*
* #param orderno
* The orderno
*/
public void setOrderno(String orderno) {
this.orderno = orderno;
}
/**
*
* #return
* The date
*/
public String getDate() {
return date;
}
/**
*
* #param date
* The date
*/
public void setDate(String date) {
this.date = date;
}
/**
*
* #return
* The noofitems
*/
public String getNoofitems() {
return noofitems;
}
/**
*
* #param noofitems
* The noofitems
*/
public void setNoofitems(String noofitems) {
this.noofitems = noofitems;
}
/**
*
* #return
* The productdetails
*/
public List<Productdetail> getProductdetails() {
return productdetails;
}
/**
*
* #param productdetails
* The productdetails
*/
public void setProductdetails(List<Productdetail> productdetails) {
this.productdetails = productdetails;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
productdetails class :
import java.util.HashMap;
import java.util.Map;
public class Productdetail {
private String pid;
private String sellingprice;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The pid
* #param s
*/
public String getPid(String s) {
return pid;
}
/**
*
* #param pid
* The pid
*/
public void setPid(String pid) {
this.pid = pid;
}
/**
*
* #return
* The sellingprice
* #param s
*/
public String getSellingprice(String s) {
return sellingprice;
}
/**
*
* #param sellingprice
* The sellingprice
*/
public void setSellingprice(String sellingprice) {
this.sellingprice = sellingprice;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Retrofit generates the json based on your POJO and set it on the post payload.
So, in this case:
#POST("/apsaratrendz/data/apsara_json_orders_document.json")
Call<Void> setOrder(#Body OrderModel orderModel);
the body of the post will be a json representation of orderModel.
If you need to change the names of the atributtes generated in the json you can use SerializedName Annotation, its very useful:
public class OrderModel {
#SerializedName("other_name_for_json")
private String name;
Hope it helps.

Having trouble using strings outside of Volley request onResponse

I have a search dialog in my MainActivity that when used sends the user query to a SearchActivity. From there I send a JSON request using volley and then deserialize the JSON using GSON. all of this is working good and I can even print, for an example, the latitude value of my request using:
System.out.println(cam[0].getLat());
However, all of this must be done within the onResponse of the volley request. I'm trying to send some of the values back to my MainActivity which I know how to do already. I just need to know how to store some of the strings so that I can access them outside of onResponse.
Method that sends request and deserializes it:
private void fetchJsonResponse() {
JsonArrayRequest req = new JsonArrayRequest(myUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Gson gson = new Gson();
String nominatimData = response.toString();
NominatimModel[] cam = gson.fromJson(nominatimData, NominatimModel[].class);
// i'd like to using cam[0].getLat(); outside of this method
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
mRequestQueue.add(req);
}
NominatimModel.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class NominatimModel {
#SerializedName("place_id")
#Expose
private String placeId;
#Expose
private String licence;
#SerializedName("osm_type")
#Expose
private String osmType;
#SerializedName("osm_id")
#Expose
private String osmId;
#Expose
private List<String> boundingbox = new ArrayList<String>();
#Expose
private String lat;
#Expose
private String lon;
#SerializedName("display_name")
#Expose
private String displayName;
#SerializedName("class")
#Expose
private String _class;
#Expose
private String type;
#Expose
private Double importance;
#Expose
private String icon;
/**
* #return The placeId
*/
public String getPlaceId() {
return placeId;
}
/**
* #param placeId The place_id
*/
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
/**
* #return The licence
*/
public String getLicence() {
return licence;
}
/**
* #param licence The licence
*/
public void setLicence(String licence) {
this.licence = licence;
}
/**
* #return The osmType
*/
public String getOsmType() {
return osmType;
}
/**
* #param osmType The osm_type
*/
public void setOsmType(String osmType) {
this.osmType = osmType;
}
/**
* #return The osmId
*/
public String getOsmId() {
return osmId;
}
/**
* #param osmId The osm_id
*/
public void setOsmId(String osmId) {
this.osmId = osmId;
}
/**
* #return The boundingbox
*/
public List<String> getBoundingbox() {
return boundingbox;
}
/**
* #param boundingbox The boundingbox
*/
public void setBoundingbox(List<String> boundingbox) {
this.boundingbox = boundingbox;
}
/**
* #return The lat
*/
public String getLat() {
return lat;
}
/**
* #param lat The lat
*/
public void setLat(String lat) {
this.lat = lat;
}
/**
* #return The lon
*/
public String getLon() {
return lon;
}
/**
* #param lon The lon
*/
public void setLon(String lon) {
this.lon = lon;
}
/**
* #return The displayName
*/
public String getDisplayName() {
return displayName;
}
/**
* #param displayName The display_name
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
* #return The _class
*/
public String getClass_() {
return _class;
}
/**
* #param _class The class
*/
public void setClass_(String _class) {
this._class = _class;
}
/**
* #return The type
*/
public String getType() {
return type;
}
/**
* #param type The type
*/
public void setType(String type) {
this.type = type;
}
/**
* #return The importance
*/
public Double getImportance() {
return importance;
}
/**
* #param importance The importance
*/
public void setImportance(Double importance) {
this.importance = importance;
}
/**
* #return The icon
*/
public String getIcon() {
return icon;
}
/**
* #param icon The icon
*/
public void setIcon(String icon) {
this.icon = icon;
}
}
Example JSON:
[{"place_id":"115063146","licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright","osm_type":"way","osm_id":"258132245","boundingbox":["29.7156836","29.7278762","-95.3520172","-95.3349753"],"lat":"29.7214917","lon":"-95.3440202128152","display_name":"University of Houston, 4800, Calhoun Road, Houston, Harris County, Texas, 77004, United States of America","class":"amenity","type":"university","importance":0.84733963787614,"icon":"http:\/\/nominatim.openstreetmap.org\/images\/mapicons\/education_university.p.20.png"}]
I'm fairly new to java and Android development so if someone can help me out a bit i'd appreciate it and if I left out any information let me know.
Figured I'd answer this question now that time has passed and I've learned a ton about Android, including how to accomplish this. So I had all my models implement Serializable, and then just bundled the response data and passed it to the other activity. I later, got rid of this and was able to accomplish everything I needed within the onResponse.
I'd steer away from using Serializable if you must do what I was trying to accomplish and instead check out the Parcelable interface, it has the advantage of being faster.
Hope this helps to anyone who comes across this question!

Java How create a set of object with two classes?

I have a logical problem to understand, how create a private set of inhabitant object. Here my two classes:
package main;
import java.util.Set;
/**
* #author
* #version 0.1
*
*/
public class City {
private String name;
/**
*HERE is my Problem*/
private Set<Inhabitants> Inhabitants {
}
/**
* standard cunstructor
*/
public City(String n, ) {
setName(n);
}
/**
* Search a particular name of inhabitant
* #return object of inhabitant
*/
static Set<Inhabitants> Search(){
return inhabitants;
}
/**
* Creates a inhabitant object and
* add to the set of inhabitants of the city
*
* #param name
* #param datebirth
* #param maritalStatus
* #
*/
public void Add(String name,String datebirth,String maritalStatus) {
}
/**
* Return all inhabitants objects of the city
* #return
*/
static Set<Inhabitants> ReturnAll(){
return inhabitants;
}
/**
* Return city name
* #return
*/
static Set<Inhabitants> ReturnCityName(){
return inhabitants;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the inhabitants
*/
public Set<Inhabitants> getInhabitants() {
return inhabitants;
}
/**
* #param inhabitants the inhabitants to set
*/
public void setInhabitants(Set<Inhabitants> inhabitants) {
this.inhabitants = inhabitants;
}
}
package main;
/**
* #version 0.1
*/
public class Inhabitants {
private String name;
private String datebirth;
private Boolean maritalStatus;
/**
* standard constructor
*/
public Inhabitants() {
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the datebirth
*/
public String getDatebirth() {
return datebirth;
}
/**
* #param datebirth the datebirth to set
*/
public void setDatebirth(String datebirth) {
this.datebirth = datebirth;
}
/**
* #return the maritalStatus
*/
public Boolean getMaritalStatus() {
return maritalStatus;
}
/**
* #param maritalStatus the maritalStatus to set
*/
public void setMaritalStatus(Boolean maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
It sounds like a simple problem. You didn't need so much code:
package collections;
/**
* Person
* #author Michael
* #link https://stackoverflow.com/questions/30958832/java-how-create-a-set-of-object-with-two-classes
* #since 6/20/2015 5:06 PM
*/
public class Person {
private final String name;
public Person(String name) {
if (name == null || name.trim().length() == 0) throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName() {
return name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name.equals(person.name);
}
#Override
public int hashCode() {
return name.hashCode();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Person{");
sb.append("name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
package collections;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* City
* #author Michael
* #link https://stackoverflow.com/questions/30958832/java-how-create-a-set-of-object-with-two-classes
* #since 6/20/2015 5:06 PM
*/
public class City {
private Set<Person> inhabitants;
public City(Collection<Person> inhabitants) {
this.inhabitants = (inhabitants == null) ? new HashSet<Person>() : new HashSet<Person>(inhabitants);
}
public void addInhabitant(Person p) {
if (p != null) {
this.inhabitants.add(p);
}
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("City{");
sb.append("inhabitants=").append(inhabitants);
sb.append('}');
return sb.toString();
}
}

JAXB #XmlAttribute #XmlValue real example

I'm new to JAXB and have troubles with conversion from XML to a Java class instance.
I have the following XML:
<?xml version="1.0"?>
<response>
<category>client</category>
<action>Greeting</action>
<code>1000</code>
<msg>Your Connection with API Server is Successful</msg>
<resData>
<data name="svDate">2009-02-16 06:22:21</data>
</resData>
</response>
and I develop the following Java code:
/**
* Copyright 2013. ABN Software. All Rights reserved.<br>
* Author ...... Andre<br>
* Created ..... 14.03.2013<br>
* <br>
*/
package net.regmaster.onlinenic.model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import net.regmaster.onlinenic.enumtype.OnicEnumAction;
import net.regmaster.onlinenic.enumtype.OnicEnumCategory;
import net.regmaster.onlinenic.model.resdata.GreetingResData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author annik
*
*/
#XmlRootElement(name = "response")
// #XmlType( propOrder = { "category", "action", "code", "message"})
public class OnicGreeting
{
private OnicEnumCategory category;
private OnicEnumAction action;
private Integer code;
private String message;
private GreetingResData resData;
//
private Logger LOG = LoggerFactory.getLogger(getClass());
/**
* Getter.
*
* #return the category
*/
public OnicEnumCategory getCategory() {
return category;
}
/**
* Setter.
*
* #param category
* the category to set
*/
public void setCategoryEnum(OnicEnumCategory category) {
this.category = category;
}
#XmlElement
public void setCategory(String category) {
try {
this.category = OnicEnumCategory.getEnum(category);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the action
*/
public OnicEnumAction getAction() {
return action;
}
/**
* Setter.
*
* #param action
* the action to set
*/
public void setActionEnum(OnicEnumAction action) {
this.action = action;
}
#XmlElement
public void setAction(String action) {
try {
this.action = OnicEnumAction.getEnum(action);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the code
*/
#XmlElement
public Integer getCode() {
return code;
}
/**
* Setter.
*
* #param code
* the code to set
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* Getter.
*
* #return the message
*/
#XmlElement(name = "msg")
public String getMessage() {
return message;
}
/**
* Setter.
*
* #param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Getter.
*
* #return the resData
*/
#XmlElementRef
public GreetingResData getResData() {
return resData;
}
/**
* Setter.
*
* #param resData
* the resData to set
*/
public void setResData(GreetingResData resData) {
this.resData = resData;
}
#Override
public String toString() {
return "category=" + category + ", action=" + action + ", code=" + code + ", msg=" + message
+ ", resData:" + resData.toString();
}
}
and
/**
* Copyright 2013. ABN Software. All Rights reserved.<br>
* Author ...... Andre<br>
* Created ..... 14.03.2013<br>
* <br>
*/
package net.regmaster.onlinenic.model.resdata;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* #author annik
*
*/
#XmlRootElement(name="resData")
public class GreetingResData extends AbstractResData
{
String svDate;
/**
* Constructor.
*
*/
public GreetingResData() {
// TODO Auto-generated constructor stub
}
/**
* Getter.
*
* #return the svDate
*/
#XmlAttribute
public String getSvDate() {
return svDate;
}
/**
* Setter.
*
* #param svDate
* the svDate to set
*/
public void setSvDate(String svDate) {
this.svDate = svDate;
}
}
These code examples run but data is wrong :
http://i.stack.imgur.com/qCCIM.png
Please help me.
Also I do not understand in case I will have many different
<data ...>..</data>
What could I do easy and simply?
I mean this case:
<resData>
<data name="crDate">2004-12-17</data>
<data name="exDate">2009-01-02</data>
<data name="password">7fe11fd9d97ee40bdf57e561427c0a6</data>
<data name="dns">dns1.onlinenic.net</data>
<data name="dns">dns2.onlinenic.net</data>
<data name="r_name">123456</data>
<data name="r_org">123456</data>
<data name="r_country">BJ</data>
<data name="r_province">mokcup</data>
<data name="r_city">123456</data>
<data name="r_street">123456</data>
<data name="r_postalcode">123456</data>
<data name="r_voice">+86.5925391800</data>
<data name="r_fax">+86.5925391800</data>
<data name="r_email">asdfasdf#sadf.com</data>
....
Thank you Blaise Doughan.
But after dug more over 10 topics I decide I HAD TO to start with opposite way.
I created new test which MARSHALLING my data (objects). Actually, I used TDD (test Driven Development) way I think.
So, I filled up my Objects with test data and applied Marshalling (created XML from DATA) and saw that I got. Data Was Incorrect. I looked to other topic also (thanx this one Java/JAXB: Unmarshall Xml to specific subclass based on an attribute ) and correct my data Structure
remember Id like to get
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<code>1000</code>
<message>Big message</message>
<resData>
<data name="svDate">2013.03.14</data>
</resData>
</response>
Now my data are :
package net.regmaster.onlinenic.model.response.resdata;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;
/**
* #author annik
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="data")
//#XmlCustomizer(ResDataCustomiser.class)
public class XmlData
{
#XmlAttribute(name="name")
private String name;
#XmlValue
private String value;
/** Getter.
* #return the name
*/
public String getName() {
return name;
}
/** Setter.
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/** Getter.
* #return the value
*/
public String getValue() {
return value;
}
/** Setter.
* #param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
and :
package net.regmaster.onlinenic.model.response.resdata;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* #author annik
*
*/
#XmlRootElement
public class ResData
{
private List<XmlData> data;
/**
* Getter.
*
* #return the data
*/
public List<XmlData> getData() {
return data;
}
/**
* Setter.
*
* #param data
* the data to set
*/
public void setData(List<XmlData> data) {
this.data = data;
}
}
and :
package net.regmaster.onlinenic.model.response;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import net.regmaster.onlinenic.enumtype.OnicEnumAction;
import net.regmaster.onlinenic.enumtype.OnicEnumCategory;
import net.regmaster.onlinenic.model.response.resdata.ResData;
import net.regmaster.onlinenic.model.response.resdata.XmlData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author annik
*
*/
#XmlRootElement(name = "response")
//#XmlType( propOrder = { "category", "action", "code", "message"})
public class OnicGreetingResponse
{
private OnicEnumCategory category;
private OnicEnumAction action;
private Integer code;
private String message;
// private GreetingResData resData;
private ResData resData;
//
#XmlTransient
private Logger LOG = LoggerFactory.getLogger(getClass());
/**
* Getter.
*
* #return the category
*/
public OnicEnumCategory getCategory() {
return category;
}
/**
* Setter.
*
* #param category
* the category to set
*/
public void setCategoryEnum(OnicEnumCategory category) {
this.category = category;
}
#XmlElement
public void setCategory(String category) {
try {
this.category = OnicEnumCategory.getEnum(category);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the action
*/
public OnicEnumAction getAction() {
return action;
}
/**
* Setter.
*
* #param action
* the action to set
*/
public void setActionEnum(OnicEnumAction action) {
this.action = action;
}
#XmlElement
public void setAction(String action) {
try {
this.action = OnicEnumAction.getEnum(action);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the code
*/
#XmlElement
public Integer getCode() {
return code;
}
/**
* Setter.
*
* #param code
* the code to set
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* Getter.
*
* #return the message
*/
#XmlElements(value={#XmlElement})
public String getMessage() {
return message;
}
/**
* Setter.
*
* #param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/** Getter.
* #return the resData
*/
public ResData getResData() {
return resData;
}
/** Setter.
* #param resData the resData to set
*/
#XmlElement
public void setResData(ResData resData) {
this.resData = resData;
}
#Override
public String toString() {
return "category=" + category + ", action=" + action + ", code=" + code + ", msg=" + message
+ ", resData:" + resData.toString();
}
}
and vu-alja :
I got that !
And as you can see below it works to another way :
http://i.stack.imgur.com/35nzb.png

Categories