I am trying to convert Java Object to JSON using Groovy JsonBuilder
Java POJO Class
public class Employee {
String name;
int age;
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Groovy Script
Employee employee = new Employee();
employee.name="Vinod"
employee.age=24
println new JsonBuilder( employee ).toPrettyString()
Output
{
}
I am not sure if I am using JsonBuilder incorrectly. Please help
Since you are using a Java POJO, you need to add the getters for the two properties you have, i.e., public String getName() and public String getAge().
The JsonBuilder leverages DefaultGroovyMethods.getProperties to get object properties. If you don't add the aforementioned getters, it does not find any properties and therefore the resulting JSON is empty.
So that:
Employee.java
public class Employee {
String name;
int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
#Override
public String toString() {
return String.format("Employee{name=%s, age=%d}", name, age);
}
}
If you use a POGO instead (Plain Old Groovy Object), getters are added by default for each property, so it works out of the box:
Related
I'm setting up a RestController using Spring-boot. This project requires me to return a list of object (in this case objects of class Book). How do I do that?
I've tried Arrays.asList() method by passing a object of class Book shown below:
java
#RestController
public class BookController {
#GetMapping("/books")
public List<Book> getAllBooks() {
return Arrays.asList(new Book(1l, "Book name", "Book author"));
}
}
java
public class Book {
Long id;
String name;
String author;
public Book(Long id, String name, String author) {
super();
this.id = id;
this.name = name;
this.author = author;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
#Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
}
}
I've got this error "Type mismatch: cannot convert from List<Object> to List<Book>". How can I fix this?
It happened to me several times, and the reason was always that IDE somehow auto imported other Arrays class, from junit package, not the one from java.util.
So check your imports part and put import java.util.Arrays; if another Arrays class is imported instead.
#Tom Hawtin - tackline suggested similar, but nothing else is needed except correct import.
My professor just went over mutable and immutable, and gave us this coding exercise to complete.
1) Create a Customer object called customer with initial values of 1 and "Cust1"
respectively.
2) Display the customer object to the screen using the toString() method.
3) Create a String object reference called name and assign to it the customer's name.
4) Assign the value "Bo Beep" to the object reference name.
5) Display the customer object to the screen using the toString() method.
The output should look like this.
Customer{id=1, name=Cust1}
Customer{id=1, name=Cust1}
I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.
Any input is helpful, thanks!
Here's my main class,
package hw01;
public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");
public static void main(String[] args) {
System.out.println(customer);
System.out.print(customer);
}
}
And here's my Customer class.
package hw01;
public class Customer {
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + '}';
}
}
Sounds like for #3 it should be something like this:
String name = customer.getName();
and then #4 would be:
name = "Bo Peep";
The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".
I have the following class
public class Patient implements Serializable {
private int id;
private String name;
private String desc;
public Patient(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc=desc;
}
And then the following getter and setter methods in this class.
Declaring the arraylist
ArrayList<Patient> list = new ArrayList<Patient>();
Adding run time data in the list
list.add(new Patient(id++, name.getText(), disDesc.getText())
Now i want the read the elements stored in the list
How can i do that?
System.out.println(list.get(0));
I use this but it returns the object address of the class
You have to override the toString() method of Patient. There, you will return all information on the Patient object that you want to display.
Example: (my personal favorite)
private static final String SEPARATOR = ", ";
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("ID: ").append(id).append(SEPARATOR);
builder.append("Name: ").append(name).append(SEPARATOR);
builder.append("Desc: ").append(desc);
return builder.toString();
}
Example 2:
#Override
public String toString()
{
return "ID: " + id + ", Name: " + name + ", Desc: " + desc;
}
Example 3:
#Override
public String toString()
{
return MessageFormat.format("ID: {0}, Name: {1}, Desc: {2}", id, name, desc);
}
Use either one. It is a matter of preference.
You have to cast the element,
((Patient) list.get(0)).getName();
And you must add a public getter method to your Patient class.
I have a Java Class like this:
public class Employee {
String Name;
int Id;
int Age;
void setName(String tempVal) {
Name = tempVal;
System.out.println(Name);
System.out.println("\n");
}
void setId(int parseInt) {
Id = parseInt;
System.out.println(Id);
System.out.println("\n");
}
void setAge(int parseInt) {
Age = parseInt;
System.out.println(Age);
System.out.println("\n");
}
}
Now I want to parse a employees.xml file using SAXParser using the code in the link: http://totheriver.com/learn/xml/xmltutorial.html#5.2
The problem is when I am adding the tempEmp to the list and accessing the list to print its value in printData() method, the output is something like:
No of Employees '3'.
Employee#140de537
Employee#1c43882a
Employee#15a08be5
Now, how do I extract the name, age and id of the employee individually?
I guess you are adding the Employee object to the list and printing the objects directly from list.If you dont override the toString() method, it will call the toString() method of Object class(superclass of all class), which will be returing the classname#hashcode(hashcode of object).If you want to print some data from your class, you need to override toString() method in your class and return the format you require.
You have to implement a toString() method in the Employee class for it to be displayed correctly, something along these lines:
#Override
public String toString() {
return Id + " " + Name + " " + Age;
}
Also, remember that in Java attribute names should start with a lowercase character, not uppercase.
You want to add some getter methods.
You should also check out the code conventions for Java - some of your variables start with an uppercase letter where they should not.
To get each value individually, you need to add a few get methods
public String getName()
{
return Name;
}
public int getAge()
{
return Age;
}
public int getId()
{
return Id;
}
I have a user defined class, say
import java.util.Calendar;
public class Employee{
private String name;
private int age;
private Calendar dob;
private Address address;
private boolean married;
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 Calendar getDob() {
return dob;
}
public void setDob(Calendar dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
class Address{
private int doorNo;
private String streetName;
private String city;
public int getDoorNo() {
return doorNo;
}
public void setDoorNo(int doorNo) {
this.doorNo = doorNo;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I am creating an object of Employee and populating it with setters. I have to represent the above object to string (encrypted or human-readable) and parse back to get similar object. Actually, I want to save the string equivalent of java object in a file and to read back them to get a java object. I know we have object writing, but they are sensitive to edit. I would prefer if a java object can be converted to String of human readable form. Thanks.
To keep your flattened object human readable and hand editable consider encoding your object into a JSON string using one of the popular JSON libraries. Same JSON library will also provide you APIs to decode a JSON string into your object.
One of the popular JSON library is Gson. Here's an use example: Converting JSON to Java
You should override toString() to convert instances of your class to string. As for recreating instances based on their string representation you can define a static factory method for this.
public class Employee {
...
#Override
public String toString() {
...
}
public static Employee fromString(String str) {
...
}
}
You use these methods like this:
To obtain string representation of an instance to string:
Employee john = ...
String johnString = john.toString();
Note that your toString() method will also be called implicitly whenever there is a need to obtain string representation of one of the instances.
To recreate an instance from string:
Employee john = Employee.fromString(johnString);
If you often need to store instances of the class in a file and read them back, you may also consider serialization. See documentation for Serializable interface as well as ObjectInputStream and ObjectOutputStream. You may also want to familiarize yourself with caveats surrounding serialization by reading the last chapter ("Serialization") in Effective Java, second edition. Most importantly be aware that the serialized form of your class becomes part of your public API.
You might be looking for the toString method:
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.
In your case you would be doing something of the sort (to be added in each of your classes):
#Override
public String toString()
{
return "Name = " + name + ...
}
The string can be of any format you wish. To save the object, all that you need to do is to write the text that the toString method returns to a file.
To read them back, however, you will have to implement your own logic. On the other hand, what you can do, is to use something such as XStream (instructions here) which will automatically convert your object to XML.
XML is human readable so that your users can modify whatever they need. Once this is done, you can re-use XStream to read back your object.
Try this
Employee em = new Employee;
//Your code
str obj= JavaScriptSerializer.Serialize();
// whenever you want to get object again
Employee emp = (Employee)JavaScriptSerializer.Deserialize();