Here is the problem, when I send my object to server using retrofit I got it null. I'm doing this to create the json object:
HashMap<String, UserModel> map = new HashMap<>();
map.put("user", user);
But, when the json arrives in the server I got something like this:
{"user":null}
Then I printed ny json file with this line:
Log.d("TAG", new JSONObject(map).toString());
And I saw the same null object.
So, here is my question, Why is this happening? And how can I fix that?
Here goes some information about my project:
Retrofit version: 2.0.0
Retrofit serializer: jackson version 2.0.0
using also jackson to convert JodaTime version 2.4.0
here goes how I get retrofit instance:
public T buildServiceInstance(Class<T> clazz){
return new Retrofit.Builder().baseUrl(BuildConfig.API_HOST)
.addConverterFactory(JacksonConverterFactory.create())
.build().create(clazz);
}
I call that method here:
public static final IUserApi serviceInstance = new ApiBuildRequester<IUserApi>()
.buildServiceInstance(IUserApi.class);
Method declaration on interface IUserApi:
#POST("User.svc/Save")
Call<ResponseSaveUserApiModel> save(#Body HashMap<String, UserModel> map);
And at last, but I guess, not less important:
public class UserModel implements Parcelable {
private String idUser;
private String name;
private String email;
#JsonProperty("password")
private String safePassword;
private String salt;
private String phoneNumber;
private String facebookProfilePictureUrl;
private String facebookUserId;
public UserModel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSafePassword() {
return safePassword;
}
public void setSafePassword(String safePassword) {
this.safePassword = safePassword;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getFacebookProfilePictureUrl() {
return facebookProfilePictureUrl;
}
public void setFacebookProfilePictureUrl(String facebookProfilePictureUrl) {
this.facebookProfilePictureUrl = facebookProfilePictureUrl;
}
public String getFacebookUserId() {
return facebookUserId;
}
public void setFacebookUserId(String facebookUserId) {
this.facebookUserId = facebookUserId;
}
#Override
public int describeContents() {
return 0;
}
public UserModel(Parcel in) { // Deve estar na mesma ordem do "writeToParcel"
setIdUser(in.readString());
setName(in.readString());
setEmail(in.readString());
setSafePassword(in.readString());
setPhoneNumber(in.readString());
setFacebookProfilePictureUrl(in.readString());
setFacebookUserId(in.readString());
}
#Override
public void writeToParcel(Parcel dest, int flags) { //Deve estar na mesma ordem do construtor que recebe parcel
dest.writeString(idUser);
dest.writeString(name);
dest.writeString(email);
dest.writeString(safePassword);
dest.writeString(phoneNumber);
dest.writeString(facebookProfilePictureUrl);
dest.writeString(facebookUserId);
}
public static final Parcelable.Creator<UserModel> CREATOR = new Parcelable.Creator<UserModel>(){
#Override
public UserModel createFromParcel(Parcel source) {
return new UserModel(source);
}
#Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
Debug screen:
#Selvin and #cricket_007 You are the best!
I got this using your hint that my printing was wrong, and I found the solution.
I have two types of users in my app, facebook users or native users, two forms, but just one object, and here was the problem, when I sent facebook objects (complete) it worked fine, but when I tried to send native users, with some null properties, it crashed my serialization.
So I had to check every property before send it, it's just a workaround, but for now it's enough, thank you a lot folks!
Related
I noticed that my bot didn't set RichPresence any more than I looked at it today. The last time I checked it was on Wednesday and the code worked there as well. So I executed it again today and the RichPresence was not re-set as usual. Now I think Discord will have changed its interface.
Now I got the latest JDA version into my project and adapted the code so that the DataObject became a JSONObject and it still didn't work. As 2nd I tried to make my "Spielst" object a RichPresence object. Unfortunately, this didn't work either.
Old Class:
public class Spielst implements Activity {
private String name;
private String url;
private ActivityType type;
public static Spielst getSpielt(String name, String url, ActivityType typ){
return new Spielst(name,url,typ);
}
protected Spielst(String name, String url, ActivityType typ) {
this.name = name;
this.url = url;
this.type = typ;
}
#Override
public boolean isRich() {
return false;
}
#Override
public RichPresence asRichPresence() {
return null;
}
#Override
public String getName() {
return name;
}
#Override
public String getUrl() {
return url;
}
#Override
public ActivityType getType() {
return type;
}
#Nullable
#Override
public Timestamps getTimestamps() {
return null;
}
public void setPresence(OnlineStatus status, String state, String details, String application_id,
String large_image, String small_image, String large_text, String small_text,
long timestamp, long since){
if(Bot.getInstance().getBot() == null)
return;
PresenceImpl presence = new PresenceImpl((JDAImpl) Bot.getInstance().getBot()).setCacheActivity(this)
.setCacheStatus(status);
JSONObject data = presence.getFullPresence();
JSONObject game = data.getJSONObject("game");
game.put("state",state);
game.put("details", details);
game.put("application_id", application_id);
JSONObject assets = new JSONObject();
game.put("timestamps",new JSONObject().put("start",timestamp));
assets.put("large_image", large_image);
assets.put("small_image", small_image);
assets.put("large_text", large_text);
assets.put("small_text", small_text);
game.put("assets",assets);
game.put("since",since);
data.put("game",game);
((JDAImpl) Bot.getInstance().getBot())
.getClient().send((new JSONObject()).put("d", data).put("op", 3).toString());
System.out.println((new JSONObject()).put("d", data).put("op", 3).toString());
}
}
new Class:
package de.letsplaybar.discordbot.main.utils;
import de.letsplaybar.discordbot.main.Bot;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.ActivityFlag;
import net.dv8tion.jda.api.entities.RichPresence;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.EnumSet;
/**
* #author Letsplaybar
* Created on 05.09.2017.
*/
public class Spielst implements RichPresence {
private String name;
private String url;
private ActivityType type;
private OnlineStatus status;
private String state;
private String details;
private String application_id;
private String large_image;
private String small_image;
private String large_text;
private String small_text;
private long timestamp;
private long since;
public static Spielst getSpielt(String name, String url, ActivityType typ,OnlineStatus status, String state, String details, String application_id,
String large_image, String small_image, String large_text, String small_text,
long timestamp, long since){
return new Spielst(name,url,typ,status,state,details,application_id,large_image,small_image,large_text,small_text,timestamp, since);
}
protected Spielst(String name, String url, ActivityType typ,OnlineStatus status, String state, String details, String application_id,
String large_image, String small_image, String large_text, String small_text,
long timestamp, long since) {
this.name = name;
this.url = url;
this.type = typ;
}
#Override
public boolean isRich() {
return false;
}
#Override
public RichPresence asRichPresence() {
return null;
}
#Override
public String getName() {
return name;
}
#Override
public String getUrl() {
return url;
}
#Override
public ActivityType getType() {
return type;
}
#Nullable
#Override
public Timestamps getTimestamps() {
return null;
}
public void setPresence(){
Bot.getInstance().getBot().getPresence().setActivity(this);
}
#Override
public long getApplicationIdLong() {
return Long.parseLong(application_id);
}
#Nonnull
#Override
public String getApplicationId() {
return application_id;
}
#Nullable
#Override
public String getSessionId() {
return "4b2fdce12f639de8bfa7e3591b71a0d679d7c93f";
}
#Nullable
#Override
public String getSyncId() {
return "e7eb30d2ee025ed05c71ea495f770b76454ee4e0";
}
#Override
public int getFlags() {
return ActivityFlag.JOIN_REQUEST.getOffset();
}
public long getTimestamp() {
return timestamp;
}
public long getSince() {
return since;
}
#Override
public EnumSet<ActivityFlag> getFlagSet() {
return EnumSet.of(ActivityFlag.JOIN_REQUEST);
}
#Nullable
#Override
public String getState() {
return state;
}
#Nullable
#Override
public String getDetails() {
return details;
}
#Nullable
#Override
public Party getParty() {
return new Party("party1234", 1, 6);
}
#Nullable
#Override
public Image getLargeImage() {
return new Image(getApplicationIdLong(), large_image, large_text);
}
#Nullable
#Override
public Image getSmallImage() {
return new Image(getApplicationIdLong(), small_image, small_text);
}
}
but by the new class, I miss the syncid and the seasonid and I also don't know where I get them from, because they are not in the documentation on the discordwebsite. has anyone found an implementation that still works for the old version or does anyone know how to get to the two values?
JDA is library made for bot accounts. Since bots can't use rich presence at all it doesn't actually support setting it. Furthermore there is no real support by discord's API for setting it this way.
The correct way to use rich presence is through an IPC connection with the discord-rpc SDK or Game SDK.
You can use a java library for the discord-rpc SDK like java-discord-rpc which connects to your Discord client and sets the presence there.
Updating rich presence through the gateway session (like JDA uses) is not documented behavior and subject to change.
Bots can't have a rich presence. Sending a request manually to Discord won't help you. If you're selfbotting, that's against the Discord TOS.
trying to access JSON data from the following:
{"actions":[{"actionType":0,"email":"contact#tonyspizza.com","faIcon":"fa-envelope",
"name":"Contact Us","subject":"Email from Tony's Pizza App"},
{"actionType":2,"faIcon":"fa-phone","name":"Call Us","number":"5204558897"}],
"total":2}
I'm trying to use retrofit to access the 'actions' as each individual classes. (i.e. ActionEmail, ActionPhone, etc). I cannot figure out a way to separate these into separate classes and not have one class with all the properties.
Thanks in advance!
Call<ActionWrapperObject> getActions(// Put your api call body in there);
Here is your ActionWrapperObject
public class ActionWrapperObject {
ArrayList<ActionModel> actions;
public ArrayList<ActionModel> getActions() {
return actions;
}
public void setActions(ArrayList<ActionModel> actions) {
this.actions = actions;
}
}
Here is your ActionModel
public class ActionModel {
int actionType;
String email;
String faIcon;
String name;
String subject;
public int getActionType() {
return actionType;
}
public void setActionType(int actionType) {
this.actionType = actionType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFaIcon() {
return faIcon;
}
public void setFaIcon(String faIcon) {
this.faIcon = faIcon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
You in your response
Your api call.enqueue(new Callback<ActionWrapperObject>() {
#Override
public void onResponse(Call<ActionWrapperObject> call, Response<ActionWrapperObject> response) {
ActionWrapperObject actionWrapperObj= response.body();
if (actionWrapperObj!= null) {
ArrayList<ActionModel> actionModelList= actionWrapperObj.getActions();
//Here you got the list of actions. Do what ever you want with them. You can
// differentiate each action on its type.
}
}
What I infer is you want to generate fields of the ActionModel class dynamically. You can refer to generating JSON pojo dynamically using reflection.
I am building an Android app that uses socket.IO to communicate with a server. On the socket I am receiving the following message:
{"id":"presenterResponse","response":"accepted","sdpAnswer":"v=0\r\no=- 3689503004 3689503004 IN IP4 0.0.0.0\r\ns=Kurento Media Server\r\nc=IN IP4 0.0.0.0\r\nt=0 0\r\na=msid-semantic: WMS ARDAMS\r\na=group:BUNDLE audio video\r\nm=audio 1 UDP/TLS/RTP/SAVPF 111 0\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=mid:audio\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=rtpmap:0 PCMU/8000\r\na=setup:active\r\na=sendrecv\r\na=rtcp-mux\r\na=fmtp:111 minptime=10; useinbandfec=1\r\na=maxptime:60\r\na=ssrc:3140217435 cname:user2918705367#host-8692fd1\r\na=ice-ufrag:aYIP\r\na=ice-pwd:sKftuHNg7pyX0FocNO0qh/\r\na=fingerprint:sha-256 33:B4:A7:4B:89:64:D2:54:AF:6B:FE:D4:5D:EF:4E:D6:AB:6F:11:B1:E7:31:87:D6:0D:22:3F:53:83:08:B7:73\r\nm=video 1 UDP/TLS/RTP/SAVPF 100\r\na=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=mid:video\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=rtpmap:100 VP8/90000\r\na=rtcp-fb:100 ccm fir\r\na=rtcp-fb:100 nack\r\na=rtcp-fb:100 nack pli\r\na=rtcp-fb:100 goog-remb\r\na=setup:active\r\na=sendrecv\r\na=rtcp-mux\r\na=ssrc:2322920152 cname:user2918705367#host-8692fd1\r\na=ice-ufrag:aYIP\r\na=ice-pwd:sKftuHNg7pyX0FocNO0qh/\r\na=fingerprint:sha-256 33:B4:A7:4B:89:64:D2:54:AF:6B:FE:D4:5D:EF:4E:D6:AB:6F:11:B1:E7:31:87:D6:0D:22:3F:53:83:08:B7:73\r\nm=application 0 DTLS/SCTP 5000\r\na=inactive\r\na=mid:data\r\na=ice-ufrag:igJW\r\na=ice-pwd:skfFXPCVLtGwABgXg9xsMO\r\na=fingerprint:sha-256 33:B4:A7:4B:89:64:D2:54:AF:6B:FE:D4:5D:EF:4E:D6:AB:6F:11:B1:E7:31:87:D6:0D:22:3F:53:83:08:B7:73\r\n"}
What I want to do now is to map this object on the following POJO class:
import org.webrtc.SessionDescription;
public class User {
private String id;
private String response;
private String name;
private String room;
private String email;
private String sdpOffer;
private SessionDescription sdpAnswer;
private String userType;
public User(){};
public SessionDescription getSdpAnswer() {
return sdpAnswer;
}
public void setSdpAnswer(SessionDescription sdpAnswer) {
this.sdpAnswer = sdpAnswer;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getSdpOffer() {
return sdpOffer;
}
public void setSdpOffer(String sdpOffer) {
this.sdpOffer = sdpOffer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
So far I have tried to transform the message in a JSONObject JSONObject j = new JSONObject(message); and populate my own object from the JSONObject but it didn't work.
How can I map the string on User class?
EDIT:
the message comes over socket.IO from a Node.js server in this way:
In the node server I send the message by send.("new message",JSON.stringfy("sdpAnswer":sdpAnswer));
On the android client I read it like:
LoginActivity.mSocket.on("new message", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i( TAG, "message back:received ");
JSONObject j = new JSONObject(args[0]); // this throws an error
Object = new JSONObject(args[0].toString());
Log.i(TAG, "The received string is " + obj.toString()); //this throws java.lang.error can not convert from string to json object
}
)};
use Gson
String jsonString = "{jsonstringhere}";
User user= new Gson().fromJson(jsonString, User.class);
Use Gson library.
Add dependency to build.gradle file.
compile 'com.google.code.gson:gson:2.8.0'
And parse json to object:
Gson gson = new Gson();
User user= gson.fromJson(message, User.class);
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 am new to implement Azure Mobile Service. I have refer the demo of ToDoItem given by Azure.
In same manner i have make class User for my own app. Then I am inserting the data in to the MobileServiceTable but it gives me error like below:
{"message":"The operation failed with the following error: 'A null store-generated value was returned for a non-nullable member 'CreatedAt' of type 'CrazyLabApp.Models.User'.'."}
I have not created any field like this as it is not created in ToDoItem demo as well. I have seen that there are 4 fields that are by Default created by the MobileServiceTable. createdAt is one of the field of that.
I am wonder about whats wrong i am doing.
Check my below Userclass:
public class User {
#com.google.gson.annotations.SerializedName("id")
private String ServiceUserId;
#com.google.gson.annotations.SerializedName("email")
private String Email;
#com.google.gson.annotations.SerializedName("firstname")
private String FirstName;
#com.google.gson.annotations.SerializedName("lastname")
private String LastName;
#com.google.gson.annotations.SerializedName("profilepic")
private String ProfilePic;
#com.google.gson.annotations.SerializedName("introduction")
private String Introduction;
#com.google.gson.annotations.SerializedName("website")
private String Website;
#com.google.gson.annotations.SerializedName("title")
private String Title;
#com.google.gson.annotations.SerializedName("_createdAt")
private Date CreatedAt;
#com.google.gson.annotations.SerializedName("coverimage")
private ArrayList<CoverImage> CoverImages;
/*public Date getCreatedAt() {
return CreatedAt;
}
public void setCreatedAt(Date createdAt) {
CreatedAt = createdAt;
}*/
#com.google.gson.annotations.SerializedName("followers")
private ArrayList<User> Followers;
#com.google.gson.annotations.SerializedName("likes")
private ArrayList<Likes> Likes;
#com.google.gson.annotations.SerializedName("collections")
private ArrayList<Collections> Collections;
#com.google.gson.annotations.SerializedName("comments")
private ArrayList<Comments> Comments;
#com.google.gson.annotations.SerializedName("stories")
private ArrayList<Story> Stories ;
//-------------- Methods
public ArrayList<Story> getStories() {
return Stories;
}
public void setStories(ArrayList<Story> stories) {
Stories = stories;
}
public ArrayList<com.promact.crazylab.model.Comments> getComments() {
return Comments;
}
public void setComments(ArrayList<com.promact.crazylab.model.Comments> comments) {
Comments = comments;
}
public ArrayList<com.promact.crazylab.model.Collections> getCollections() {
return Collections;
}
public void setCollections(ArrayList<com.promact.crazylab.model.Collections> collections) {
Collections = collections;
}
public ArrayList<com.promact.crazylab.model.Likes> getLikes() {
return Likes;
}
public void setLikes(ArrayList<com.promact.crazylab.model.Likes> likes) {
Likes = likes;
}
public ArrayList<User> getFollowers() {
return Followers;
}
public void setFollowers(ArrayList<User> followers) {
Followers = followers;
}
public ArrayList<CoverImage> getCoverImages() {
return CoverImages;
}
public void setCoverImages(ArrayList<CoverImage> coverImages) {
CoverImages = coverImages;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getWebsite() {
return Website;
}
public void setWebsite(String website) {
Website = website;
}
public String getIntroduction() {
return Introduction;
}
public void setIntroduction(String introduction) {
Introduction = introduction;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getServiceUserId() {
return ServiceUserId;
}
public void setServiceUserId(String serviceUserId) {
ServiceUserId = serviceUserId;
}
#Override
public boolean equals(Object o) {
return o instanceof User && ((User) o).ServiceUserId == ServiceUserId;
}
}
Also check below code the way i am inserting it:
final User u = new User();
u.setFirstName(mName);
u.setEmail(mEmail);
u.setProfilePic(mUrl);
mUserTable = mClient.getTable(User.class);
// Insert the new item
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final User entity = mUserTable.insert(u).get();
} catch (Exception e){
//createAndShowDialog(e, "Error");
System.out.println("Error: "+e.toString());
}
return null;
}
}.execute();
Please help me in this.
The "_createdat" column will be populated automatically by Azure Mobile Services so there is no need to include it in your model. Delete this property from the User class. Its presence is probably overwriting the auto-populated value with a null.
you can solve this problem by just deleting createdAt column from your user table in azure.
Why this error is coming :
I am not sure But I guess this error is coming because createdAt is a non-nullable member and you cannot left it null.
EDIT :
Another aspect of the system columns is that they cannot be sent by the client. For new tables (i.e., those with string ids), if an insert of update request contains a property which starts with ‘__’ (two underscore characters), the request will be rejected. The ‘__createdAt’ property can, however, be set in the server script (although if you really don’t want that column to represent the creation time of the object, you may want to use another column for that) – one way where this (rather bizarre) scenario can be accomplished. If you try to update the ‘__updatedAt’ property, it won’t fail, but by default that column is updated by a SQL trigger, so any updates you make to it will be overridden anyway.
for more info take a look here :-http://blogs.msdn.com/b/carlosfigueira/archive/2013/11/23/new-tables-in-azure-mobile-services-string-id-system-properties-and-optimistic-concurrency.aspx