I have followed this tutorial to build REST API using Spring boot. It taught alot. But What I am trying to do really got me stuck.
What I am trying to get is:
{
"marks":{
"id":"1",
"name":"test",
"remark":"passed",
"course": {
"id": "1",
"name": "Spring Boot",
"description": "Solves many problems",
"topic": {
"id": "1",
"name": "Java",
"description": "Powerful Programming Language"
}
}
But I get the error when I tried to add the marks- as :
{
"timestamp": 1515600105327,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.web.bind.MissingPathVariableException",
"message": "Missing URI template variable 'courseId' for method parameter of type String",
"path": "/topics/1/courses/1/marks"
}
My Marks Model is:
public class Marks {
#Id
private String id;
private String name;
private String remark;
#ManyToOne
private Course course;
#ManyToOne
private Topic topic;
public Marks() {
}
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public Marks(String id, String name, String remark,String topicId, String courseId) {
this.id = id;
this.name = name;
this.remark = remark;
this.topic = new Topic(topicId, "","");
this.course = new Course(courseId, " ", " ", " ");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}
And MarksController.java:
public class MarksController {
#RestController
public class MarksController {
#Autowired
private MarksService marksService;
#RequestMapping("/topics/{topicId}/courses/{id}/marks")
public List<Marks> getAllMarks(#PathVariable String courseId) {
return marksService.getAllMarks(courseId);
}
#RequestMapping(method=RequestMethod.POST, value="/topics/{topicId}/courses{courseId}/marks")
public void addMarks(#RequestBody Marks marks,#PathVariable String topicId ,#PathVariable String courseId) {
marks.setTopic(new Topic(topicId, "", ""));
marks.setCourse(new Course(courseId, "", "", ""));
marksService.addMarks(marks);
}
}
And MarksService.java:
public class MarksService {
#Service
public class MarksService {
#Autowired
private MarksRepository marksRepository;
public void addMarks(Marks marks) {
marksRepository.save(marks);
}
}
And MarksRepository.java:
public interface MarksRepository extends CrudRepository<Marks, String> {
public List<Marks> findByCourseId(String courseId);
public List<Marks> findByTopicId(String topicId);
}
Can anyone help me get the result as in the mentioned JSON.
For the POST method
This:
/topics/{topicId}/courses{courseId}/marks
Should be:
/topics/{topicId}/courses/{courseId}/marks
Note the additional / between courses and {courseId}
For the GET method
This:
/topics/{topicId}/courses/{id}/marks
Should be:
/topics/{topicId}/courses/{courseId}/marks
Note the use of courseId to agree with the parameter name in MarksController.getAllMarks.
Related
Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();
I have been fighting with Retrofit 2.3 for about 2 weeks now. The List always comes back as empty for me. It simply makes a call and gets the JSON information yet it won't process the list.
Json appears like this:
{
"users": [
{
"id": 2,
"name": "Users Name",
"username": "myusername",
"facebook_id": null,
"level": "1",
"birthdate": "1999-09-09T00:00:00+00:00",
"email": "user#gmail.com",
"activated": "",
"created": "2017-12-07T04:18:30+00:00",
"answers": [
{
"id": 31,
"question_id": 2,
"user_id": 2,
"answer": "School",
"questions": [
{
"id": 2,
"question": "Where did you meet your best friend?"
}
]
},
{
"id": 32,
"question_id": 3,
"user_id": 2,
"answer": "Dog",
"questions": [
{
"id": 3,
"question": "What was your first pet's name?"
}
]
}
]
}
],
"message": "Success"
}
Retrofit Interface class:
public interface RestInterface {
String url = "http://myurl.com";
/**
* Login
*
* #param username Username
* #param password Password
*
*/
#FormUrlEncoded
#Headers("User-Agent:My-Application")
#POST("login")
Call<userlogin> Login(#Field("username") String username,
#Field("password") String password);
}
Userlogin class:
public class userlogin {
#SerializedName("users")
#Expose
private List<users> users;
#SerializedName("message")
#Expose
private Object message;
public List<users> getUsers() {
return users;
}
public void setUsers(List<users> users) {
this.users = users;
}
public Object getMessage() {
return message;
}
public void setMessage(Object message) {
this.message = message;
}
}
users class:
public class users {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("username")
#Expose
private String username;
#SerializedName("facebook_id")
#Expose
private String facebookId;
#SerializedName("level")
#Expose
private String level;
#SerializedName("birthdate")
#Expose
private String birthdate;
#SerializedName("email")
#Expose
private String email;
#SerializedName("activated")
#Expose
private String activated;
#SerializedName("created")
#Expose
private String created;
#SerializedName("answers")
#Expose
private List<Answer> answers = null;
public users(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFacebookId() {
return facebookId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getActivated() {
return activated;
}
public void setActivated(String activated) {
this.activated = activated;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
Basically what happens is when it is called my "message" part comes back "Successful" which on my PHP side basically just states there were no errors. If there were any then it would return the error for display.
When trying to get the users information it always comes back with an empty List.
My response is always the same:
03-14 20:06:26.698 30995-30995/com.josh.testapp D/Response: {"message":"Success","users":[]}
03-14 20:06:26.699 30995-30995/com.josh.testapp I/System.out: Users:: []
03-14 20:06:26.699 30995-30995/com.josh.testapp D/Message: Success
I'm not sure what it is I'm missing. The users should be coming back as a list containing user information, in this case just the information of the user logging in. But in other parts, this will display sub-users information as well which is why it is in List form in the first place.
Please help or guide me in the right direction.
login.java (where the call is made)
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RestInterface.url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestInterface restInterface = retrofit.create(RestInterface.class);
Call<userlogin> call = restInterface.Login(
username.getText().toString(), // username
pass.getText().toString() // password
);
call.enqueue(new Callback<userlogin>() {
#Override
public void onResponse(Call<userlogin> call, retrofit2.Response<userlogin> response) {
if (response.isSuccessful()) {
userlogin ul = response.body();
try{
String res = new Gson().toJson(response.body());
Log.d("Response", res);
System.out.println("Users:: " + ul.getUsers().toString());
Log.d("Message", ul.getMessage().toString());
List<users> userList = ul.getUsers();
for(int i = 0; i < userList.size(); i++){
Log.d("Users", userList.get(i).getUsername());
}
} catch (Exception e){
Log.d("exception", e.getMessage());
}
} else {
Log.d("unSuccessful", response.message());
}
}
#Override
public void onFailure(Call<userlogin> call, Throwable t) {
Log.d("onFailure", t.getMessage());
}
});
After AbdulAli pointed out that it appeared to not be receiving the users list I decided to look over my code and run a few more tests on the server API. I discovered there was an issue with sessions. They weren't picking up and therefor returned a "Successful" yet empty user list. After implementing some CookieJar functions in I was able to pass my cookie for sessions and the user list was no longer empty.
While I feel like an idiot for missing something so obvious, I am very grateful for you pointing that out AbdulAli.
i found myself in a situation where i need to get some data with POST on my server and do some simple stuff with it. But it keeps saying 415 Unsupported Media Type when i try to test it with www.hurl.it website.
This is my json that i am sending:
{
"pictures": {
"picture": [
{
"id": "1",
"name": "10_aut_linen_male_less_student_work_yellow_n_cold.png"
},
{
"id": "2",
"name": "10_aut_linen_male_less_student_work_yellow_n_mild.png"
},
{
"id": "3",
"name": "10_aut_linen_male_less_student_work_yellow_n_hot.png"
}
]
}
}
this is the model class:
package com.models.sm7;
import java.util.ArrayList;
import java.util.List;
public class Sm7Pictures {
private Pictures pictures;
public Pictures getPictures() {
return pictures;
}
public void setPictures(Pictures pictures) {
this.pictures = pictures;
}
public class Pictures {
private List<Picture> picture = new ArrayList<Picture>();
public List<Picture> getPicture() {
return picture;
}
public void setPicture(List<Picture> picture) {
this.picture = picture;
}
}
public class Picture {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
This is my service class :
#Path("sm7Service")
public class Sm7Service {
Sm7DAO sm7DAO = new Sm7DAO();
#GET
#Path("/testSm7")
#Produces(MediaType.TEXT_PLAIN)
public String testSm (){
return "Hello";}
#POST
#Path("/checkPictures")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public String getPictures(Sm7Pictures picture){
System.out.println("pokrenuto");
return "Hello";}
}
the DAO class is where i will do all my logic, but for testing purpouses i've just put text plain... I am really banging my head over this :S because it is simple but i can not get it to work. my bet is that it has something to do with the model class? Please help!
Solved it, had to put {} inside #Consumes(MediaType.APPLICATION_JSON) like this #Consumes({MediaType.APPLICATION_JSON}).
I'm encountering problem with my android app for REST service.
I got following json response from server:
{
"0": {
"id": 1,
"name": "Some Guy",
"email": "example1#example.com"
},
"1": {
"id": 2,
"name": "Person Face",
"email": "example2#example.com"
},
"3": {
"id": 3,
"name": "Scotty",
"email": "example3#example.com",
"fact": {
"hobbies": ["fartings", "bikes"]
}
}
}
My objects are:
User class:
public class User {
#SerializedName("id")
private
int id;
#SerializedName("name")
private
String name;
#SerializedName("email")
private
String email;
#SerializedName("fact")
private
Fact fact;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Fact getFact() {
return fact;
}
public void setFact(Fact fact) {
this.fact = fact;
}
public User(){}
}
Fact class:
public class Fact {
#SerializedName("hobbies")
private List<Hobbies> hobbies;
public List<Hobbies> getHobbies() {
return hobbies;
}
public void setHobbies(List<Hobbies> hobbies) {
this.hobbies = hobbies;
}
public Fact(){}
}
Hobbies class:
public class Hobbies {
private String hobby;
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Hobbies(){}
}
When I use below code in my app:
private User jsonToUser(String result){
User users = null;
if(result != null && result.length() > 0){
Gson gson = new GsonBuilder().create();
users = gson.fromJson(result, User.class);
}
return users;
}
Object returned by function is filled by nulls. I've tried to use class Users which is empty and extends ArrayList
public class Users extends ArrayList<User> {
//
}
and app was giving me error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
I wish to use it for:
ArrayAdapter<User> adapter = new ArrayAdapter<User>(activity, android.R.layout.simple_list_item_1, users);
Could you tell me what I'm doing wrong, please? It worked for my twitter timeline app, but doesn't wor for this.
Your code users = gson.fromJson(result, User.class); would work, if you want to convert a JSON string like { "id": 1, "name": "Some Guy", "email": "example1#example.com" } into one User object.
But a JSON string like yours
{
"0": {
"id": 1,
"name": "Some Guy",
"email": "example1#example.com"
},
...
}
is interpreted as an Array (or HashMap?!) of User objects.
Try the following using Array:
users = gson.fromJson(result, User[].class);
or (if GSON interprets it as a HashMap):
users = gson.fromJson(result, HashMap<String, User>.class);
The more elegant way using code from Collections example from the Gson user guide would be using Collection:
Type collectionType = new TypeToken<Collection<User>>(){}.getType();
Collection<User> users= gson.fromJson(result, collectionType);
In the "Collections limitations" part is written the following:
While deserializing, Collection must be of a specific generic type
I'm not sure, but that could mean, that you have to to set collectionType to use List and not Collection as specific type.
or (if GSON interprets it as a HashMap):
Type hashMapType = new TypeToken<HashMap<String, User>>(){}.getType();
HashMap<String, User> users= gson.fromJson(result, hashMapType);
Good luck =)
EDIT
My try with the last solution was successul:
public class User {
private String id, name, email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public static void main(String[] args) {
String result = ""
+ "{\"0\": { \"id\": 1, \"name\": \"Some Guy\", \"email\": \"example1#example.com\"},"
+ "\"1\": { \"id\": 2, \"name\": \"Person Face\", \"email\": \"example2#example.com\"}"
+ "}";
Gson gson = new Gson();
Type hashMapType = new TypeToken<HashMap<String, User>>() {
}.getType();
HashMap<String, User> users = gson.fromJson(result, hashMapType);
for (String key : users.keySet()) {
printUser(users.get(key));
}
}
private static void printUser(User user) {
System.out.printf("%s %s %s\n", user.getId(), user.getName(),
user.getEmail());
}
My problem:
I`ve built a rest client within my iphone-application with restkit 0.20.
My RESTService was built with jax-rs including jackson.
There is one class named "Customer", where I hold my customer data.
#XmlRootElement
public class Customer extends BaseEntity {
private int customer_id;
private String appell;
private String firstname;
private String lastname;
private Date birthday;
private String street;
private String streetnr;
private String zipcode;
private String place;
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getAppell() {
return appell;
}
public void setAppell(String appell) {
this.appell = appell;
}
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getStreetnr() {
return streetnr;
}
public void setStreetnr(String streetnr) {
this.streetnr = streetnr;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
What can I do? Why there's always this error logged in RestKit:
Expected status code in (200-299), got 400" UserInfo=0x956e2f0 {NSLocalizedRecoverySuggestion=Unrecognized field "customer" (Class customer.model.Customer), not marked as ignorable
I don't have a field named customer.
Here is my POST method:
#POST
#Path("/insert")
#Consumes(MediaType.APPLICATION_JSON)
public Response insertCustomer(Customer customer) {
String result = "Customer inserted " + customer.getLastname();
customer.createEntity();
return Response.status(201).type(MediaType.APPLICATION_JSON).entity(result).build();
}
This is an example of a generated JSON object (Jackson), when a #GET method is called within my ios application.
{
"appell": "Frau",
"birthday": "1991-10-01T00:00:00+01:00",
"customer_id": "3",
"firstname": "Max",
"lastname": "Mustermann",
"place": "München",
"street": "Einsteinweg",
"streetnr": "19",
"zipcode": "81858"
}
And this is an example of the JSON object, when my ios application calls the showed #POST method:
{"customer":{"streetnr":"19",
"zipcode":"81829",
"customer_id":0,
"place":"München",
"appell":"Herr",
"firstname":"Heinrich",
"birthday":"1991-10-01T00:00:00+01:00",
"lastname":"Maier",
"street":"Lehrer-Wirth-Str.19"}}
I am a absolute newbie using restkit and jax-rs.
I just added a #GET method for requesting xml format.
Here you can see it:
#GET
#Path("/listallcustomers")
#Produces(MediaType.APPLICATION_XML)
public ArrayList<Customer> showAllCustomers() {
ArrayList<Customer> list = DBAccess.getInstance().getAllCustomers();
return list;
}
and this is the result:
<customers>
<customer>
<appell>Frau</appell>
<birthday>1991-10-01T00:00:00+01:00</birthday>
<customer_id>3</customer_id>
<firstname>Max</firstname>
<lastname>MUstermann</lastname>
<place>München</place>
<street>Einsteinstr.</street>
<streetnr>19</streetnr>
<zipcode>82838</zipcode>
</customer>
...
My #GET method which creates a JSON object is the following:
#GET
#Path("/listall")
#Produces(MediaType.APPLICATION_JSON)
public ArrayList<Customer> showAllJsonCustomers() {
ArrayList<Customer> list = DBAccess.getInstance().getAllCustomers();
return list;
}
and this an example of a JSON object it creates:
{
"lastname": "Müller",
"customer_id": 6,
"appell": "Herr",
"firstname": "pupsi",
"birthday": "1986-10-16",
"street": "Lehrer-Wirth-Str",
"streetnr": "19",
"zipcode": "81829",
"place": "München"
},
...