Retrofit post request null body - java

I'm trying to post my data in json format. I think I'm doing it right, but it's making the mistake:
body = null, response code =417
Json data needs to post in the following format:
{
"Users": [{
'Phone': 'xxxxxxxxxxx',
'Name': 'yyyyy'
}
]
}
My code is all:
#POST("api")
#FormUrlEncoded
Call<TRList> savePost(#Field("Phone") String Phone,
#Field("Name") String Name);
}
}
public class UsersList {
#SerializedName("Users")
#Expose
private List<Post> users = null;
public List<Post> getUsers() {
return users;
}
public void setTr(List<Post> users) {
this.users = users;
}
}
public class Post {
#SerializedName("Phone")
#Expose
private String phone;
#SerializedName("AS")
#Expose
private String Name;
//getter and setter methods
}
public void sendPost(Post post){
mAPIService.savePost(post.getPhone().toString(),post.getName().toString()).enqueue(new Callback<UsersList>() {
#Override
public void onResponse(Call<UsersList> call, Response<UsersList> response) {
Log.d("requestError", "onResponse: "+ call.request().body().toString());
if(response.isSuccessful()) {
showResponse(response.body().toString());
}
}

Please check below code
First create Output class
Create class User
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("Phone")
#Expose
private String phone;
#SerializedName("Name")
#Expose
private String name;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create class UserList
public class UserList {
#SerializedName("Users")
#Expose
private List<User> users = null;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
for input class you already have post class
public class Post {
#SerializedName("Phone")
#Expose
private String phone;
#SerializedName("AS")
#Expose
private String Name;
//getter and setter methods
}
on your interface create this method
#POST("api")
Call<UserList> savePost(##Body Post post);
call service
public void sendPost(Post post){
mAPIService.savePost(post).enqueue(new Callback<UserList>() {
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
Log.d("requestError", "onResponse: "+ call.request().body().toString());
if(response.isSuccessful()) {
showResponse(response.body().toString());
}
}

Related

Retrofit Body isn't showing desired response from Nested JSON

I've been trying to connect an Android App to the Fitbit API using Retrofit however I'm struggling with getting a connection to a JSON with a nested user section. I've managed to get the classes set up however get Body: com.example.myapplication.User#6fe68c1 when requesting the body back.
Whilst learning about Retrofit I've had no problems with using however this seems to be different because of the "user" in the JSON.
Shortened JSON I'm working from
{
"user": {
"age": 23,
"avatar": "https://static0.fitbit.com/images/profile/defaultProfile_100.png",
"averageDailySteps": 2673,
"dateOfBirth": "1999-01-25",
"displayName": "Name.",
"features": {
"exerciseGoal": true
},
"fullName": "Full Name",
"gender": "MALE",
"glucoseUnit": "METRIC",
"height": 180.3,
"memberSince": "2022-02-28",
"startDayOfWeek": "MONDAY",
"strideLengthRunning": 123.10000000000001,
"weight": 72.5,
}
}
Fitbit Class
imports
#Generated("jsonschema2pojo")
public class Fitbit {
#SerializedName("user")
#Expose
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Class
imports
#Generated("jsonschema2pojo")
public class User {
#SerializedName("age")
#Expose
private Integer age;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("averageDailySteps")
#Expose
private Integer averageDailySteps;
#SerializedName("dateOfBirth")
#Expose
private String dateOfBirth;
#SerializedName("fullName")
#Expose
private String fullName;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("height")
#Expose
private Double height;
#SerializedName("memberSince")
#Expose
private String memberSince;
#SerializedName("startDayOfWeek")
#Expose
private String startDayOfWeek;
#SerializedName("strideLengthRunning")
#Expose
private Double strideLengthRunning;
#SerializedName("strideLengthWalking")
#Expose
private Double strideLengthWalking;
#SerializedName("timezone")
#Expose
private String timezone;
#SerializedName("waterUnitName")
#Expose
private String waterUnitName;
#SerializedName("weight")
#Expose
private Double weight;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Integer getAverageDailySteps() {
return averageDailySteps;
}
public void setAverageDailySteps(Integer averageDailySteps) {
this.averageDailySteps = averageDailySteps;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public String getMemberSince() {
return memberSince;
}
public void setMemberSince(String memberSince) {
this.memberSince = memberSince;
}
public String getStartDayOfWeek() {
return startDayOfWeek;
}
public void setStartDayOfWeek(String startDayOfWeek) {
this.startDayOfWeek = startDayOfWeek;
}
public Double getStrideLengthRunning() {
return strideLengthRunning;
}
public void setStrideLengthRunning(Double strideLengthRunning) {
this.strideLengthRunning = strideLengthRunning;
}
public Double getStrideLengthWalking() {
return strideLengthWalking;
}
public void setStrideLengthWalking(Double strideLengthWalking) {
this.strideLengthWalking = strideLengthWalking;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getWaterUnitName() {
return waterUnitName;
}
public void setWaterUnitName(String waterUnitName) {
this.waterUnitName = waterUnitName;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
}
JsonPlaceholderAPI Interface Class
imports
public interface JsonPlaceholderAPI {
#Headers({"Authorization: Bearer bearercodeinserted"})
#GET("https://api.fitbit.com/1/user/-/profile.json")
Call<User> getUser();
}
MainActivity
public class MainActivity extends AppCompatActivity {
private TextView textViewResult;
private JsonPlaceholderAPI jsonPlaceholderAPI;
#Override
protected void onCreate(Bundle savedInstanceState) {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceholderAPI = retrofit.create(JsonPlaceholderAPI.class);
getUser();
}
private void getUser() {
Call<User> call = jsonPlaceholderAPI.getUser();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code: " + response.code());
return;
}
textViewResult.setText("Body: " + response.body());
}
#Override
public void onFailure(Call<User> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
Solution:
Change Call<User>() to Call<Fitbit>()
and response.body().getUser().toString()
If you want textViewResult.setText("Body: " + response.body()); to give you string representation of your User data you have to override toString() function on your User object. For example:
public class User {
#SerializedName("age")
#Expose
...
#Override
String toString() {
return "age: " + age + " avatar: " + avatar + ....;
}
}

Why the object is returned empty? Android. Retrofit2

Why the object is returned empty? Android. Retrofit2.
I have a class User:
public class User{
#SerializedName("LOGIN")
String login;
#SerializedName("PASSWORD")
String password;
#SerializedName("NAME")
String name;
#SerializedName("SURNAME")
String surname;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
This's my JSON:
[{
"LOGIN":"TEST",
"PASSWORD":"TEST",
"NAME":"TEST",
"SURNAME":"TEST"
}
]
Interface:
public interface Link {
#GET("93sZY0Xg")
Call<List<User>> listRepos();
}
and class LoginActivity where i use retrofit2:
public class LoginActivity extends AppCompatActivity implements Callback<List<User>>{
private Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://pastebin.com/raw/")
.build();
private Link service = retrofit.create(Link.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Call<List<User>> us = service.listRepos();
us.enqueue(this);
}
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
System.out.println(response.body());
System.out.println(response.code());
User us = response.body().get(0);
System.out.println(us.getName());
for(User m: response.body()){
System.out.println( m.getName());
}
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
System.out.println(t.getLocalizedMessage());
}
}
I get this response: response.code() is 200;
I/System.out: [com.example.com.dataBase.User#b789a]
I tried getName from class User, but all variables is null.
Why are the values empty? Where's my mistakes?
Try following, expose annotation is important to set value in fields
#Expose
#SerializedName("movie_id")
private String movieId;
#Expose
#SerializedName("movie_name")
private String movieName;
#Expose
#SerializedName("movie_poster")
private String moviePoster;
#Expose
#SerializedName("movie_dialog_count")
private String movieDialogCount;

How can i convert json string to java object in android?

I am trying to convert the response from server which is a JSON string,I want to convert that JSONstring to java object.I am trying Gson.Please someone explain and tell me the steps how to do it using Gson.
#Override
public void onClick(View v) {
if (v == mLoginButton) {
LoginUser();
}
if (v==mSignUpBtn){
Intent intent=new Intent(LoginActivity.this,RegistrationActivity.class);
startActivity(intent);
}
}
private void LoginUser() {
// final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest postStringRequest = new StringRequest(Request.Method.POST,LOGIN_API,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();
Log.d(TAG,"Reponse Check :"+response);
// Gson gson = new Gson();
// String jsonInString = "{}";
//LoginActivity staff = gson.fromJson(jsonInString, LoginActivity.class);
//Log.d(TAG,"Reponse Check staff :"+staff);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG,"Error Response Check :"+error);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Log.d(TAG,"For email :"+email);
Log.d(TAG,"For password :"+password);
//try {
Log.d(TAG,"My Credentials email URL Encoder: "+( mEncryption.AESEncode(email)));
Log.d(TAG,"My Credentials email URL DECODED: "+( mEncryption.AESDecode(mEncryption.AESEncode(email))));
params.put("data[User][email]",(mEncryption.AESEncode(email)));
Log.d(TAG,"My Credentials pass URL Encoder: "+( mEncryption.AESEncode(password)));
paa
}
logcat
03-16 16:36:08.346 2618-3428/com.example.user.myapplication D/Null: For email :abc#gmail.com
03-16 16:36:08.346 2618-3428/com.example.user.myapplication D/Null: For password :12345678
03-16 16:36:08.354 2618-3428/com.example.user.myapplication D/Null: My Credentials email URL Encoder: RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=
03-16 16:36:08.358 2618-3428/com.example.user.myapplication D/Null: My Credentials email URL DECODED: abc#gmail.com
03-16 16:36:08.360 2618-3428/com.example.user.myapplication D/Null: My Credentials pass URL Encoder: pfrt1fKLkoZhAT6hoMJFiA==
03-16 16:36:08.361 2618-3428/com.example.user.myapplication D/Null: Params :{data[User][password]=pfrt1fKLkoZhAT6hoMJFiA==
, data[User][email]=RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=
}
03-16 16:36:08.505 2618-2618/com.example.user.myapplication D/Null: Reponse Check :{"code":200,"user":{"User":{"id":"ui1bJkK19jxbaquTboA2oQ==","email":"RyUMRBg7UyeIlFBBtNemZFuG46PJtAIdiZWXnlJ4zNI=","status":"1","verified":"1","created":"2016-03-07 11:41:59","modified":"2016-04-07 15:43:43","token":"6b987332b77d7c69d76bf7be80a85177fb7fa08d"},"Profile":{"id":"1","first_name":"abc","last_name":"fgh","bio":"sfafaf","address":"82, Debinibash Road\r\nDum Dum, P.O. - Motijheel","phone":"+913325505055","profile_pic":"\/img\/356a192b7913b04c54574d18c28d46e6395428ab\/license.jpg","user_id":"1","Contributor":{"id":"31","profile_id":"1","status":"1","vs_cdn_id":"261961777","secret_token":"s-7Va5z","uploaded_on":null,"statement":"AOK KJDHKJDH bkgkg kkhkjh kjhkj kjh kjhkjh","time":"7 hours per month","created":"2016-05-02 18:40:11","modified":"2016-05-02 18:41:29"},"Moderator":[]},"redirect":"\/"}}
You can use in a generic way like:
private final static Gson GSON = new GsonBuilder().create();
public static <T> T fromJSON(String json, Class<T> clazz) {
try {
return GSON.fromJson(json, clazz);
} catch (JsonSyntaxException e) {
LOGGER.warn("Could not deserialize object", e);
}
return null;
}
You can't make activity/fragment from json.
In your onResponse() method:
ModelObject obj = new Gson().fromJson(jsonString, ModelObject.class);
And make ModelObject class something like this:
public class ModelObject {
int field1;
int field2;
//here you should make getters and setters;
}
After it you can do anything you need with this object (pass it to any activity or fragment).
Gson will map the values to the corresponding model class object if the fields are given correctly. Have a look at the below model classes. After that, if you call Example data = GSON.fromJson(yourJson, Example.class); , this data object will have all that you need.
-----------------------------------com.example.Contributor.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Contributor {
#SerializedName("id")
#Expose
private String id;
#SerializedName("profile_id")
#Expose
private String profileId;
#SerializedName("status")
#Expose
private String status;
#SerializedName("vs_cdn_id")
#Expose
private String vsCdnId;
#SerializedName("secret_token")
#Expose
private String secretToken;
#SerializedName("uploaded_on")
#Expose
private Object uploadedOn;
#SerializedName("statement")
#Expose
private String statement;
#SerializedName("time")
#Expose
private String time;
#SerializedName("created")
#Expose
private String created;
#SerializedName("modified")
#Expose
private String modified;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVsCdnId() {
return vsCdnId;
}
public void setVsCdnId(String vsCdnId) {
this.vsCdnId = vsCdnId;
}
public String getSecretToken() {
return secretToken;
}
public void setSecretToken(String secretToken) {
this.secretToken = secretToken;
}
public Object getUploadedOn() {
return uploadedOn;
}
public void setUploadedOn(Object uploadedOn) {
this.uploadedOn = uploadedOn;
}
public String getStatement() {
return statement;
}
public void setStatement(String statement) {
this.statement = statement;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("user")
#Expose
private User user;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
-----------------------------------com.example.Profile.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Profile {
#SerializedName("id")
#Expose
private String id;
#SerializedName("first_name")
#Expose
private String firstName;
#SerializedName("last_name")
#Expose
private String lastName;
#SerializedName("bio")
#Expose
private String bio;
#SerializedName("address")
#Expose
private String address;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("profile_pic")
#Expose
private String profilePic;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("Contributor")
#Expose
private Contributor contributor;
#SerializedName("Moderator")
#Expose
private List<Object> moderator = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Contributor getContributor() {
return contributor;
}
public void setContributor(Contributor contributor) {
this.contributor = contributor;
}
public List<Object> getModerator() {
return moderator;
}
public void setModerator(List<Object> moderator) {
this.moderator = moderator;
}
}
-----------------------------------com.example.User.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("User")
#Expose
private User_ user;
#SerializedName("Profile")
#Expose
private Profile profile;
#SerializedName("redirect")
#Expose
private String redirect;
public User_ getUser() {
return user;
}
public void setUser(User_ user) {
this.user = user;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public String getRedirect() {
return redirect;
}
public void setRedirect(String redirect) {
this.redirect = redirect;
}
}
-----------------------------------com.example.User_.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User_ {
#SerializedName("id")
#Expose
private String id;
#SerializedName("email")
#Expose
private String email;
#SerializedName("status")
#Expose
private String status;
#SerializedName("verified")
#Expose
private String verified;
#SerializedName("created")
#Expose
private String created;
#SerializedName("modified")
#Expose
private String modified;
#SerializedName("token")
#Expose
private String token;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

how to get a subobject from json response

i'm trying to retrieve an inner object from a json response, my json pojo looks like this:
public class Pojo {
private String token;
private User user;
public Pojo()
{}
public Pojo(String username, String password,User user) {
user.setUsername(username);
user.setPassword(password);
this.user = user;
}
public String getToken() {return token;}
public void setToken(String token) {this.token = token;}
public User getUser() {return user;}
public void setUser(User user) {this.user = user;}
and my innerobjct User looks like this:
public class User {
private String username
;
private String name;
private String phone;
private String email;
private String password;
private String is_Active;
}
with their setters and getters
this is my login code:
public void onLogin(View view){
final ProgressDialog dialog = ProgressDialog.show(this, "", "loading...");
EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);
Password = tv_Password.getText().toString();
Username = tv_Username.getText().toString();
User usr = new User();
Pojo user = new Pojo(Username,Password,usr);
Call<Pojo> call = loginService.getToken(usr);
call.enqueue(new Callback<Pojo>() {
#Override
public void onResponse(Response<Pojo> response, Retrofit retrofit) {
dialog.dismiss();
if (response.isSuccess()) {
Pojo user = response.body();
if(user.getUser().getIs_Active()=="True") {
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "Wrong User or Password", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Throwable t) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error Conection", Toast.LENGTH_SHORT).show();
}
});
}
the response is comming like this:
{
"token":"tokengfsgfds"
"user":{
"username":"exmplename"
"email":"#gomail.com"
"is_active":"True"
}
}
i can retrieve the token, but when i try to get variables from the user inner object my app fails. thanks!
this just mirror code for model classes using Gson library
Pojo.java
import com.google.gson.annotations.SerializedName;
public class Pojo {
#SerializedName("token")
private String token;
#SerializedName("user")
private User user;
public Pojo(String username, String password,User user) {
// TODO Auto-generated constructor stub
user.setUsername(username);
user.setPassword(password);
this.token = "tokengfsgfds";
this.user = user;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
take User out of Pojo and make another class User.java
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("username")
private String username;
#SerializedName("name")
private String name;
#SerializedName("phone")
private String phone;
#SerializedName("email")
private String email;
#SerializedName("password")
private String password;
#SerializedName("is_Active")
private boolean is_active;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isIs_active() {
return is_active;
}
public void setIs_active(boolean is_active) {
this.is_active = is_active;
}
}
I used Gson but the output should be the same
import com.google.gson.Gson;
public class TestTwo {
public static void main(String[] args) {
User user = new User();
user.setEmail("someone#gmailcom");
user.setIs_active(true);
user.setName("Cristian");
user.setPassword("Cam");
user.setPhone("1234123441");
user.setUsername("cam.cri");
Pojo pojo = new Pojo("cam.cri", "Cam", user);
String result = (new Gson()).toJson(pojo);
System.out.println(""+result);
Pojo pojo2 = (new Gson()).fromJson(result, Pojo.class);
System.out.println("Token: \t"+pojo2.getToken());
System.out.println("email: \t"+pojo2.getUser().getEmail());
System.out.println("is_active: \t"+pojo2.getUser().isIs_active());
System.out.println("Name: \t"+pojo2.getUser().getName());
System.out.println("Password: \t"+pojo2.getUser().getPassword());
System.out.println("phone: \t"+pojo2.getUser().getPhone());
System.out.println("Username: \t"+pojo2.getUser().getUsername());
}
}
Output
{
"token": "tokengfsgfds",
"user": {
"username": "cam.cri",
"name": "Cristian",
"phone": "1234123441",
"email": "someone#gmailcom",
"password": "Cam",
"is_Active": true
}
}
output
Token: tokengfsgfds
email: someone#gmailcom
is_active: true
Name: Cristian
Password: Cam
phone: 1234123441
Username: cam.cri

Neo4J Spring relateTo function cannot be resolved

Given the following class:
package com.example.model;
import java.util.Collection;
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
import org.springframework.data.neo4j.annotation.RelatedToVia;
import org.springframework.security.core.GrantedAuthority;
#NodeEntity
public class User {
private static final String SALT = "cewuiqwzie";
public static final String FRIEND = "FRIEND";
public static final String RATED = "RATED";
#Indexed
String login;
String name;
String password;
String info;
private Roles[] roles;
public User() {
}
public User(String login, String name, String password, Roles... roles) {
this.login = login;
this.name = name;
this.password = encode(password);
this.roles = roles;
}
private String encode(String password) {
return "";
// return new Md5PasswordEncoder().encodePassword(password, SALT);
}
#RelatedToVia(elementClass = Rating.class, type = RATED)
Iterable<Rating> ratings;
#RelatedTo(elementClass = Movie.class, type = RATED)
Set<Movie> favorites;
#RelatedTo(elementClass = User.class, type = FRIEND, direction = Direction.BOTH)
Set<User> friends;
public void addFriend(User friend) {
this.friends.add(friend);
}
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
public Collection<Rating> getRatings() {
return IteratorUtil.asCollection(ratings);
}
#Override
public String toString() {
return String.format("%s (%s)", name, login);
}
public String getName() {
return name;
}
public Set<User> getFriends() {
return friends;
}
public Roles[] getRole() {
return roles;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void updatePassword(String old, String newPass1, String newPass2) {
if (!password.equals(encode(old)))
throw new IllegalArgumentException("Existing Password invalid");
if (!newPass1.equals(newPass2))
throw new IllegalArgumentException("New Passwords don't match");
this.password = encode(newPass1);
}
public void setName(String name) {
this.name = name;
}
public boolean isFriend(User other) {
return other != null && getFriends().contains(other);
}
public enum Roles implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
#Override
public String getAuthority() {
return name();
}
}
}
I get a compilation exception here:
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
Following the tutorial here. Any insight as to where this function resides is appreciated.
You're trying to use the advanced mapping mode. See the reference manual for more information. You'll need to set up AspectJ support in your IDE. Methods are woven into your entity classes at compile time.

Categories

Resources