I'm trying to parse a JSON file which I get via API to pojo. After searching on internet I see boon is working with rest but I can't figure out how.
According to this article it should work but....
In my code HTTP.getJSON() method require a map as parameter which I can't figure out what exactly this map is.
Any genius one can give a working example of boon?
public class ViewTimeline{
public void view() {
ObjectMapper mapper = JsonFactory.create();
List<String> read = IO.readLines("https://corona-api.com/timeline");
Map<String, ?> headers = null ;
List<Timeline> timelineList = mapper.readValue(HTTP.getJSON("https://corona-api.com/timeline", headers), List.class, Timeline.class);
}
}
TimeLine.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"updated_at",
"date",
"deaths",
"confirmed",
"recovered",
"active",
"new_confirmed",
"new_recovered",
"new_deaths",
"is_in_progress"
})
public class Timeline {
#JsonProperty("updated_at")
private String updatedAt;
#JsonProperty("date")
private String date;
#JsonProperty("deaths")
private Integer deaths;
#JsonProperty("confirmed")
private Integer confirmed;
#JsonProperty("recovered")
private Integer recovered;
#JsonProperty("active")
private Integer active;
#JsonProperty("new_confirmed")
private Integer newConfirmed;
#JsonProperty("new_recovered")
private Integer newRecovered;
#JsonProperty("new_deaths")
private Integer newDeaths;
#JsonProperty("is_in_progress")
private Boolean isInProgress;
#JsonProperty("updated_at")
public String getUpdatedAt() {
return updatedAt;
}
#JsonProperty("updated_at")
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
#JsonProperty("date")
public String getDate() {
return date;
}
#JsonProperty("date")
public void setDate(String date) {
this.date = date;
}
#JsonProperty("deaths")
public Integer getDeaths() {
return deaths;
}
#JsonProperty("deaths")
public void setDeaths(Integer deaths) {
this.deaths = deaths;
}
#JsonProperty("confirmed")
public Integer getConfirmed() {
return confirmed;
}
#JsonProperty("confirmed")
public void setConfirmed(Integer confirmed) {
this.confirmed = confirmed;
}
#JsonProperty("recovered")
public Integer getRecovered() {
return recovered;
}
#JsonProperty("recovered")
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
#JsonProperty("active")
public Integer getActive() {
return active;
}
#JsonProperty("active")
public void setActive(Integer active) {
this.active = active;
}
#JsonProperty("new_confirmed")
public Integer getNewConfirmed() {
return newConfirmed;
}
#JsonProperty("new_confirmed")
public void setNewConfirmed(Integer newConfirmed) {
this.newConfirmed = newConfirmed;
}
#JsonProperty("new_recovered")
public Integer getNewRecovered() {
return newRecovered;
}
#JsonProperty("new_recovered")
public void setNewRecovered(Integer newRecovered) {
this.newRecovered = newRecovered;
}
#JsonProperty("new_deaths")
public Integer getNewDeaths() {
return newDeaths;
}
#JsonProperty("new_deaths")
public void setNewDeaths(Integer newDeaths) {
this.newDeaths = newDeaths;
}
#JsonProperty("is_in_progress")
public Boolean getIsInProgress() {
return isInProgress;
}
#JsonProperty("is_in_progress")
public void setIsInProgress(Boolean isInProgress) {
this.isInProgress = isInProgress;
}
}
To parse an json to an object, I used Jackson. I also saw you used Jackson at mapping in Timeline.
Jackson Core: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.11.0
Jackson Databind: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.11.0
Jackson Annotation: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.11.0
This is the way I handled it:
public static void main(String[] args) throws JsonProcessingException {
//my method to read content from website.
//using apache http
String jsonApi = getApi();
ObjectMapper objectMapper = new ObjectMapper();
//todo JsonProcessingException
JsonNode data = objectMapper.readTree(jsonApi);
//get data field from data, which is an array
//todo This can throws error if data field is missing
JsonNode dataArray = data.get("data");
List<Timeline> timelineList = new ArrayList<>();
if(dataArray.isArray()){
for(JsonNode line : dataArray){
//todo this can throws errors. need to handle it.
Timeline timeline = objectMapper.readValue(line.toString(), Timeline.class);
timelineList.add(timeline);
}
}else{
System.out.println("JsonApi is not array: '" + jsonApi + "'");
}
System.out.println("Size: " + timelineList.size());
for(Timeline timeline : timelineList){
System.out.println(timeline.getConfirmed());
}
}
At this code you should handle the exceptions. I marked them by comments.
Related
I'm trying to store a whole array of object into one field on my oracle database, I'm referring to the solution on this question, but it kept giving me Can not set java.lang.String field xxx.demo.Models.Sensors.amplitudos to xxx.demo.Models.Sensors error, I have checked the JSON body and the entity class, but I cannot find the mistake.
Here is my code.
entity
#Entity
#Table(name = "SENSOR")
public class Sensor implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "TIMERECEIVED")
private Timestamp timereceived;
#Column(name = "SENSORS")
private Sensors[] sensors;
#Column(name = "LOC")
private String location;
public Sensor() {
}
public Sensor(Timestamp timereceived, Sensors[] sensors, String location) {
this.timereceived = timereceived;
this.sensors = sensors;
this.location = location;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Timestamp getTimereceived() {
return timereceived;
}
public void setTimereceived(Timestamp timereceived) {
this.timereceived = timereceived;
}
public Sensors[] getSensors() {
return sensors;
}
public void setSensors(Sensors[] sensors) {
this.sensors = sensors;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
Sensors class
#Embeddable
public class Sensors {
private String amplitudos;
private Double displacement;
private String frequencies;
private Integer sensorId;
public Sensors() {
}
public Sensors(String amplitudos, Double displacement, String frequencies, Integer sensorId) {
this.amplitudos = amplitudos;
this.displacement = displacement;
this.frequencies = frequencies;
this.sensorId = sensorId;
}
public String getAmplitudos() {
return amplitudos;
}
public void setAmplitudos(String amplitudos) {
this.amplitudos = amplitudos;
}
public Double getDisplacement() {
return displacement;
}
public void setDisplacement(Double displacement) {
this.displacement = displacement;
}
public String getFrequencies() {
return frequencies;
}
public void setFrequencies(String frequencies) {
this.frequencies = frequencies;
}
public Integer getSensorId() {
return sensorId;
}
public void setSensorId(Integer sensorId) {
this.sensorId = sensorId;
}
}
my JSON body
{
"timereceived": "2022-11-29T12:04:42.166",
"sensors": [
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 1
},
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 2
},
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 3
},
{
"amplitudos": "a1#a2#a3#a4",
"displacement": 0.002,
"frequencies": "f1#f2#f3#f4",
"sensorid": 4
}
],
"location": "lokasi"
}
my controller
#PostMapping("/sendData")
public ResponseEntity sendData(#RequestBody Sensor sensor) {
Sensor newSensor = sensorRepository.save(sensor);
System.out.println(newSensor);
return ResponseEntity.ok("Sensor received");
}
I have tried checking every possible solution and the problem is not fixed, my expectation is the data stored into 1 column for the sensors field in the JSON body.
The problem is with the JPA mapping, not with the Controller, I think.
You're using #Embeddable, which normally result in a set of columns in your main table. If it's a collection of #Embeddable objects, you could map it to a separate table with foreign keys, using #ElementCollection.
However, you want to store the collection of sensors as a single JSON string in a single column in your main table. For that, you do not need the #Embeddable annotation. You need to write a custom convertor to convert the collection of sensors to JSON.
public class SensorsConverter implements AttributeConverter<List<Sensors>, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
#Override
public String convertToDatabaseColumn(List<Sensors> sensors) {
return objectMapper.writeValueAsString(sensors);
}
#Override
public List<Sensors> convertToEntityAttribute(String sensorsJSON) {
return objectMapper.readValue(sensorsJSON, new TypeReference<List<Sensors>>() {});
}
}
Then you can use it in your entity class:
#Column(name = "SENSORS")
#Convert(converter = SensorsConverter.class)
private List<Sensors> sensors;
I am new to drools, please bear with me if this is a silly question. I have a class member type of Object which I am using to store JSON value (passed from frontend), due to unstructured data I am using Object type for a variable. Here's the POJO class.
public class Submission {
#Id
private String id;
private String form;
private String formId;
private Object data;
private Date createdAt = new Date();
private Date modifiedAt = new Date();
private String state;
private Boolean isDeleted = false;
private Boolean valid = false;
public Boolean getValid() {
return valid;
}
public void setValid(Boolean valid) {
this.valid = valid;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getFormId() {
return formId;
}
public void setFormId(String formId) {
this.formId = formId;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getModifiedAt() {
return modifiedAt;
}
public void setModifiedAt(Date modifiedAt) {
this.modifiedAt = modifiedAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Boolean getDeleted() {
return isDeleted;
}
public void setDeleted(Boolean deleted) {
isDeleted = deleted;
}
}
and this is my .drl
package rules;
import com.ics.lcnc.Submission.Submission;
rule "check name is correct"
when
Submission(data.name == "john")
then
submission.setValid(true)
end
But for above file I get following error when I try to load this file into KieBuilder
Message [id=3, kieBase=defaultKieBase, level=ERROR, path=rules/123.drl, line=5, column=0
text=Unable to Analyse Expression data.name == "hashim":
[Error: unable to resolve method using strict-mode: java.lang.Object.name()]
[Near : {... data.name == "hashim" ....}]
Seems like rule engine is unable to find nested property of Object data. How do I target nested property which will be known to a program at runtime only?
you may try with having the data field be converted (eg by Jackson) as a Map following a prototype based approach and then
...
when
Submission(data["name"] == "john") ...
of instead of Map have a JSONNode (and adapt the constraint in the rule), again for the data field in your Submission object model.
in this case, i want to show Json to an response page in java hibernate, query method from DAO like this:
public List<TransactionQR> getAllTransaction() throws HibernateException {
return this.session.createQuery("FROM TransactionQR tr, Batch b, Terminal t, User_Smartphone us, Merchant mc WHERE tr.batch = b.id AND b.user_smartphone = us.id AND b.terminal = t.id AND t.merchant = mc.id AND state = '1' ").list();
}
then in servlet class i try to convert the list into json using Json object and json array then write in response like this:
int start = 0;
String jsonResult = null;
JSONObject jo=new JSONObject();
HttpServletRequest request = context.getRequest();
HttpServletResponse response = context.getResponse();
HttpSession session = context.getSession();
DB db = getDB(context);
//JSONObject jo = new JSONObject();
QRTransactionDao QR = new QRTransactionDao(db);
//Gson objGson = new GsonBuilder().setPrettyPrinting().create();
//String json = objGson.toJson(QR.getAllTransaction());
//System.out.println(json);
List<TransactionQR> str = QR.getAllTransaction();
JSONArray array = new JSONArray();
for(TransactionQR tr : str){
JSONObject str3 = new JSONObject();
str3.put("amount", tr.getAmount());
context.put("jsoncontent", jsonResult);
array.add(str3);
}
jo.put("status", "ok");
jo.put("dataqr", array);
jsonResult=jo.toString();
response.setContentType("application/json");
response.getWriter().print(jsonResult);
but i got the error on syntax in this line loop:
for(TransactionQR tr : str){
the error like this:
[Ljava.lang.Object; cannot be cast to Transaction
here the model Transaction:
package id.co.keriss.consolidate.ee;
import java.io.Serializable;
import java.util.Date;
public class TransactionQR implements Serializable{
private Long id;
private String codeqr;
private Date approvaltime;
private String merchant;
private String code_merchant;
private Long amount;
private Long saldoawal;
private Integer tracenumber;
private String state;
private Date createdate;
private Batch batch;
public TransactionQR() {
}
public TransactionQR(Long id, String codeqr, Date approvaltime, String merchant, String code_merchant, Long amount,
Long saldoawal, Integer tracenumber, String state, Date createdate, Batch batch) {
super();
this.id = id;
this.codeqr = codeqr;
this.approvaltime = approvaltime;
this.merchant = merchant;
this.code_merchant = code_merchant;
this.amount = amount;
this.saldoawal = saldoawal;
this.tracenumber = tracenumber;
this.state = state;
this.createdate = createdate;
this.batch = batch;
}
public Long getId() {
return id;
}
public Date getApprovalTime() {
return approvaltime;
}
public Batch getBatch() {
return batch;
}
public void setBatch(Batch batch) {
this.batch = batch;
}
public void setApprovalTime(Date approvalTime) {
this.approvaltime = approvalTime;
}
public void setId(Long id) {
this.id = id;
}
public Date getApprovaltime() {
return approvaltime;
}
public void setApprovaltime(Date approvaltime) {
this.approvaltime = approvaltime;
}
public String getCodeqr() {
return codeqr;
}
public void setCodeqr(String codeqr) {
this.codeqr = codeqr;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getCode_merchant() {
return code_merchant;
}
public void setCode_merchant(String code_merchant) {
this.code_merchant = code_merchant;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public Long getSaldoawal() {
return saldoawal;
}
public void setSaldoawal(Long saldoawal) {
this.saldoawal = saldoawal;
}
public Integer getTracenumber() {
return tracenumber;
}
public void setTracenumber(Integer tracenumber) {
this.tracenumber = tracenumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
i have try to handle the list with Gson:
Gson objGson = new GsonBuilder().setPrettyPrinting().create();
String json = objGson.toJson(QR.getAllTransaction());
System.out.println(json);
in that way, it's work to show but it's not from POJO right i want work with pojo to parse the data to json ?
why i get the error can't cast to model ? any clue ?
Try adding Select tr to your query in getAllTransaction()
Wich is the relation between QRTransactionDao and TransactionQR ?
I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.
The request sent by the client was syntactically incorrect.
Code
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
MappingJackson2HttpMessageConverter());
ResponseEntity<Results> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Results.class);
System.err.println(">>" + responseEntity.getBody().getEvents().size());
Classes
Results
public class Results {
private List<Events> events;
getter and setter
}
Events
public class Event {
private long eventId;
private String name;
private String subTitle;
private String description;
private String localDate;
private String localDateFrom;
private String imageUrl;
private int venueId;
private String venue;
private int availableTickets;
private long performerId;
private String performer;
private String performerType;
private int subcategoryId;
private String urlCategoryName;
private String metaTitle;
private String metaDescription;
private String primeSportUrl;
private String sectionWiseView;
private String venueCity;
private String venueState;
private String snippetDate;
private int eiProductionId;
private boolean requireBillingAsShipping;
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalDateFrom() {
return localDateFrom;
}
public void setLocalDateFrom(String localDateFrom) {
this.localDateFrom = localDateFrom;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public int getAvailableTickets() {
return availableTickets;
}
public void setAvailableTickets(int availableTickets) {
this.availableTickets = availableTickets;
}
public long getPerformerId() {
return performerId;
}
public void setPerformerId(long performerId) {
this.performerId = performerId;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getPerformerType() {
return performerType;
}
public void setPerformerType(String performerType) {
this.performerType = performerType;
}
public int getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(int subcategoryId) {
this.subcategoryId = subcategoryId;
}
public String getUrlCategoryName() {
return urlCategoryName;
}
public void setUrlCategoryName(String urlCategoryName) {
this.urlCategoryName = urlCategoryName;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getPrimeSportUrl() {
return primeSportUrl;
}
public void setPrimeSportUrl(String primeSportUrl) {
this.primeSportUrl = primeSportUrl;
}
public String getSectionWiseView() {
return sectionWiseView;
}
public void setSectionWiseView(String sectionWiseView) {
this.sectionWiseView = sectionWiseView;
}
public String getVenueCity() {
return venueCity;
}
public void setVenueCity(String venueCity) {
this.venueCity = venueCity;
}
public String getVenueState() {
return venueState;
}
public void setVenueState(String venueState) {
this.venueState = venueState;
}
public String getSnippetDate() {
return snippetDate;
}
public void setSnippetDate(String snippetDate) {
this.snippetDate = snippetDate;
}
public int getEiProductionId() {
return eiProductionId;
}
public void setEiProductionId(int eiProductionId) {
this.eiProductionId = eiProductionId;
}
public boolean isRequireBillingAsShipping() {
return requireBillingAsShipping;
}
public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {
this.requireBillingAsShipping = requireBillingAsShipping;
}
}
Partial Response
[{
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
UPDATE
I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.
UPDATE
The code is returning following exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217)
at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45)
at com.myproject.web.TicketController.findTicket(TicketController.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
UPDATE
following code returns
Code
try {
System.err.println(">>> primeSport");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<Event[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",
Event[].class);
System.err.println(">>" + responseEntity.getBody().length);
System.err.println(">>" + responseEntity.getBody()[0].getEventId());
System.err.println(">>" + responseEntity.getBody()[1].getEventId());
} catch (Exception e) {
e.printStackTrace();
}
Output
>1532
>0
>0
Can you try the following and see whether helps:
ResponseEntity<Events[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Events[].class);
System.err.println(">>" + responseEntity.getBody().length);
For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.
#JsonProperty("EventId")
private long eventId;
#JsonProperty("Name")
private String name;
Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?
Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).
Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.
String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "username");
params.add("password", "password");
params.add("userid", "23");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
Please let me know, how it works out.
Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.
According to the json format, all you need is using the Event class instead of the Result class.
Or change the JSON result to this :
["events": {
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.writeValue(new File("c://temp/employee.json"), Results);
}
i can't parse JSON object to corresponding formats in my Java class. Problems were began when i try to parse MySql data type in Java Data type and MySQL time type to java data type. I was tried few different solutions from stackoverflow but i cant resolve problem. Here is my DATABASE TABLE, JSON function and JAVA Class
DATABASE TABLE
filmID int(11)
naziv varchar(50)
datum date
trajanje time
cijenaKarte float
salaID int(11)
JSON Object mapper
/**************************************************************************/
public static filmovi jsonToFilmovi(JSONObject jsonObject) {
filmovi Filmovi = null;
try {
Filmovi = new filmovi(jsonObject.getJSONArray("korisnik").getJSONObject(0).getInt("filmID"),
jsonObject.getJSONArray("filmovi").getJSONObject(0).getString("naziv"),
jsonObject.getJSONArray("filmovi").getJSONObject(0).get("datum").toString()),
jsonObject.getJSONArray("filmovi").getJSONObject(0).getString("trajanje"),
Float.parseFloat(jsonObject.getJSONArray("filmovi").getJSONObject(0).get("cijenaKarte").toString()),
jsonObject.getJSONArray("filmovi").getJSONObject(0).getInt("salaID"));
} catch (Exception e) {
Log.e("jsontToFilmovi", "JSON TO FILMOVI ERROR: " + e.getMessage());
}
return Filmovi;
}
/********************************************************************************/
JAVA CLASS
public class filmovi {
#Expose
private Integer filmID;
#Expose
private String naziv;
#Expose
private Date datum;
#Expose
private Date trajanje;
#Expose
private Float cijenaKarte;
#Expose
private Integer salaID;
public filmovi(Integer filmID, String naziv, Date datum, Date trajanje, Float cijenaKarte, Integer salaID) {
this.filmID = filmID;
this.naziv = naziv;
this.datum = datum;
this.trajanje = trajanje;
this.cijenaKarte = cijenaKarte;
this.salaID = salaID;
}
public Integer getFilmID() {
return filmID;
}
public void setFilmID(Integer filmID) {
this.filmID = filmID;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public Date getTrajanje() {
return trajanje;
}
public void setTrajanje(Date trajanje) {
this.trajanje = trajanje;
}
public Float getCijenaKarte() {
return cijenaKarte;
}
public void setCijenaKarte(Float cijenaKarte) {
this.cijenaKarte = cijenaKarte;
}
public Integer getSalaID() {
return salaID;
}
public void setSalaID(Integer salaID) {
this.salaID = salaID;
}