I am using Jersy for producing Json in an application.
The code snippet which produces Json is as follows
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("sample")
public List<test> displaySampleMessage(#PathParam("id") int id)
{
System.out.println(id);
List<test> sample1 = new ArrayList<>();
test temp1 = new test();
temp1.setName("abc");
sample1.add(temp1);
return sample1;
}
Test is simple java class with the following code
package webServiceTester;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class test
{
private String name;
private int age;
public test()
{
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public test(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
Then when I run this web service I get the following output
I do not t want to get age = 0 here because I have not set the age property of my object.
What is its solution. I want age to be appeared if I set the value otherwise it should not appear..
Use Jakson, here you can find a
JSON example with Jersey + Jackson.
So you can use #JsonSerialize annotation to exclude null or empty fields.
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
or
#JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
However it's not a good practice to exclude null or empty fields in restful applications because it may lead errors in client side.
Related
I am trying to pull a field via reflection that is an array of the below class.
package com.api.Person
public class Person {
private String name;
private int age;
public Person() {
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.client.Client
public class Client{
...
People[] peoples;
...
}
I know how to get the field I am looking for and declare my methods. So below, obj would be my People[] and methodgetAge and methodsetAge are two methods I have defined that act on a Person class. How do I take my obj and loop through it to get individual People and call methodgetAge on each person?
Class<?> mainClass = cl.loadClass("com.client.Client");
Class<?> peopleClass = cl.loadClass("com.api.Person");
Field allPersons = mainClass.getDeclaredField("peoples");
allPersons.setAccessible(true);
Object obj = allPersons.get(mainClass);
Method methodgetAge = peopleClass .getDeclaredMethod("getAge");
Method methodsetAge = peopleClass .getDeclaredMethod("setAge", int.class);
I've came upon a problem and I am struggling for 5 hours.
I've created a Java API (right now just for testing) in Eclipse using Jersey and this is my first time creating an API.
I am using Postman to test it.
When calling the GET method to just return a string "Hello" it's working great.
The problem is when I try the POST method that accepts an object of a class Person as an input parameter and also just returns string "Hello" I get Internal Server Error. I know I am not using the Person object right now, but I am just testing the input parameter from Postman and it's not working.
I tried to change the function in the API to be without an input parameter and just to be POST and it works like that, it prints the "Hello", but I need that input parameter for later...
The problem is somewhere around the creation of the object in the xml code in Postman maybe, I don't know.
Any suggestion is welcomed.
Here is the code for the API with the methods get and post
#Path("/employee")
public class API {
#POST
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
#Path("/examplepost")
public String examplePost(Person p) {
return "Hello";
}
#GET
#Consumes(MediaType.APPLICATION_XML)
#Produces(MediaType.APPLICATION_XML)
#Path("/exampleget")
public String exampleGet() {
return "Hello";
}
}
This is the Person class:
#XmlRootElement(name = "person")
public class Person {
private String name;
private int age;
private int id;
public Person(String name, int age, int id) {
super();
this.name = name;
this.age = age;
this.id = id;
}
public Person() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString(){
return id+"::"+name+"::"+age;
}
}
And these are the results from Postman
GET Method
POST Method
The problem is that the argument Person p does not have the right class type. the function is consuming an XML not an instance of Person. So you have to use JAXBElement that represents information about an Xml Element
public String examplePost(JAXBElement<Person> p) {
Person person = p.getValue();
return "Hello";
}
[OPTIONAL] Also in PostMan: you have to specify what data you are sending by adding the xml version at the beginning
<?xml version="1.0"?>
<Person>
<!-- Person's attributes -->
</Person>
I am trying to integrate gson in my Play! 2.x. I am using gson & jongo and facing this error : http://hastebin.com/agewopocen.bash
Here is my model class:
public class Person extends MongoModel<Person>
{
ObjectId _id;
String name;
int age;
public Person()
{
super(Person.class, "person");
}
public Person(String name, int age)
{
super(Person.class, "person");
this.name = name;
this.age = age;
System.out.println();
}
#Override
public Person setModel()
{
return this;
}
#Override
public ObjectId getId()
{
return null;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String toJson()
{
return new GsonBuilder().create().toJson(this);
}
#Override
public String toString()
{
return new Gson().toJson(this);
}
}
I don't know what a "TypeAdapter" is (mentioned in the error log in the above link) and I am sure that we can get this working without using it. But, I dont know what I am missing.
Here is the code I tried (without Play, in regular Java) and it works.
public class Test
{
public static void main(String[] args)
{
Person nfe = new Person(10, "nfe");
String s = new Gson().toJson(nfe);
System.out.println(s);
}
public static class Person {
int age;
String name;
public Person(int age, String name)
{
this.age = age;
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public void setName(String name)
{
this.name = name;
}
}
}
Output :
{"age":10,"name":"nfe"}
Can someone help me in fixing this?
Currently, I want to get list of selected checkbox from a table.
and I tried to have a sample code as below :
public class Student {
public List<String> listSubject;
public List<String> getListSubject() {
return listSubject;
}
public void setListSubject(List<String> listSubject) {
this.listSubject = listSubject;
}
private int id;
private String name;
private int age;
public boolean single;
public boolean isSingle() {
return single;
}
public void setSingle(boolean single) {
this.single = single;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(List<String> listSubject, int id, String name, int age,
boolean single) {
super();
this.listSubject = listSubject;
this.id = id;
this.name = name;
this.age = age;
this.single = single;
}
}
And the blow is controller
and StudentForm to add information
after selected checkbox from form, I want to display all result to a view :
But until now, I still can't controller adding selected value into a listofSubject which I created for a student.
THe blow is the link of sample code which I am implementing :
https://dl.dropboxusercontent.com/u/11576807/spring-mvc-example.zip
Besides, I want to use a tag instead of submit button to redirect to result page.
And the system only allow user to select two options, at that time, the remain checkbox will be disabled.
Can you please share with me your solution in this case ?
Please tell me know the way to do it with the sample above.
Thanks
You already found the answer. Check stu.getListSubject(). All the checked items will populated to List by Spring MVC.
Your controller should look like this.
#RequestMapping(value = "/student/add", method = RequestMethod.POST)
public String addStudent(Student stu, ModelMap model){
for (String s: stu.getListSubject()) {
//You can see values populated
System.out.println("string: " + s);
}
model.addAttribute("name",stu.getName());
model.addAttribute("age", stu.getAge());
model.addAttribute("single", stu.isSingle());
model.addAttribute("listSubject", stu.getListSubject());
return "studentView";
}
And you have error in your studentView.jsp file.
Instead of this
<c:forEach items="listSubject" var="subject">
<td>${subject}</td>
</c:forEach>
use this:
<c:forEach items="${listSubject}" var="subject">
<td>${subject}</td>
</c:forEach>
You missed ${} .
I'm looking for the following feature describe below.
The MessageFormat of the sun api doesn't fit my need & the Spring El expression too maybe.
Assuming that we have a person Object with a name:
Person person = new Person();
person.setName("fredop");
person.setAge("25");
String messageFormat="My name is {Person.name}, i'm {Person.age} years old""
System.out.println(Translate(person,messageFormat);
In the translate method, i will pass ONLY one object.
This final line will print:
"My name is fred, i'm 25 years old"
Any idea of an actual api doing that?
Groovy, that is a Java language extension toward a ruby/python like language, allows you to easily embed variables inside strings:
String s = "Hello I'm a ${groovyname} string in which i can insert ${object.variable}"
You can do this using Spring Expression Langauge. Here is the code with example:
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.ExpressionParser;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class Main {
public static void main(String[] args) {
Person p = new Person("abhinav", 24);
String expression = "my name is #{name} and my age is #{age}";
System.out.println(SpelFormatter.format(expression, p));
}
}
class SpelFormatter {
private static final ExpressionParser PARSER = new SpelExpressionParser();
private static final TemplateParserContext TEMPLATE_PARSER_CONTEXT =
new TemplateParserContext();
public static String format(String expression, Object context) {
return PARSER.parseExpression(expression,
TEMPLATE_PARSER_CONTEXT).getValue(context, String.class);
}
}
Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.
Check the User guide for syntax etc.