I want to convert the following bean class to JSON object by using Jackson library
public class Student {
String name ;
int id ;
List<Address> address;
}
I want following json
{
"Name" : "sys1",
"Id" : 1,
"address" : [some address]
}
Can anyone help me how to achieve this ?.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaToJson {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Address> addrList = new ArrayList<>();
Address addr = new Address();
addr.setArea("ABC");
addr.setCity("XYZ");
addrList.add(addr);
Student std = new Student();
std.setName("Rahul");
std.setId(1);
std.setAddress(addrList);
String json = objectMapper.writeValueAsString(std);
System.out.println(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int id;
List<Address> address;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
class Address {
String area;
String city;
public String getArea() {
return this.area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return this.area;
}
public void setCity(String city) {
this.city = city;
}
}
Related
This is my dto class and I try to map the field of entity becuse I want to use that in the service layer.
Blockquote
package com.prolifics.dto;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(Include.NON_NULL)
public class FacilityDTO {
private Integer id;
private String city;
private String name;
private String pin;
private String state;
private String status;
private float lattitude;
private float longitude;
private Map<String,Integer> vaccineStock;
public Map<String, Integer> getVaccineStock() {
return vaccineStock;
}
public void setVaccineStock(Map<String, Integer> vaccineStock) {
this.vaccineStock = vaccineStock;
}
public float getLattitude() {
return lattitude;
}
public void setLattitude(float lattitude) {
this.lattitude = lattitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
In my facilityVaccineEntity there is a stock variable of int type and I want to map that field in my dto class as it does not contain stock field so that I can access it from service class. how to do this?
#Repository
public interface FacilityVaccineRepository extends CrudRepository<FacilityVaccine,Integer>{
public FacilityVaccine stock(int stock);
}
I am using JSON-B for output object to json and there is a circular reference in the object (please do not ask me to remove the circular reference), sample code as follows
The Person class contains a list of Property
and the Property class reference back the person which form a circular reference.
In the first print the json can be output, however in the second print statement, stack overflow error due to touch the circular reference of the object, I do not want to use #JsonbTransient to ignore any of them, how can I solve this?
I am expecting the json output as
{"id":1,"name":"Jhon","propertyList":[{"person":1, "propertyName":"Palace"},{"person":1, "propertyName":"Apartment"}]}
Sample Code:
import java.util.ArrayList;
import java.util.List;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class JsonTest {
public static void main(String[] args) throws InterruptedException {
Person person = new Person(1, "Jhon");
Jsonb jsonb = JsonbBuilder.create();
//no error as no property is added
System.out.println("jsonPerson without property: " + jsonb.toJson(person));
Property p1 = new Property();
p1.setPropertyName("Palace");
p1.setPerson(person);
Property p2 = new Property();
p2.setPropertyName("Apartment");
p2.setPerson(person);
person.getPropertyList().add(p1);
person.getPropertyList().add(p2);
/**
* stackoverflow here
*/
System.out.println("jsonPerson with property: " + jsonb.toJson(person));
}
public static class Property {
private Person person;
private String propertyName;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
}
public static class Person {
private int id;
public Person() {
super();
}
public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}
private String name;
private List<Property> propertyList = new ArrayList<>();
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 List<Property> getPropertyList() {
return propertyList;
}
public void setPropertyList(List<Property> propertyList) {
this.propertyList = propertyList;
}
}
}
Finally I give up using JSON-B and instead use Jackson, use the annotation #JsonIdentityInfo here is my solution for information:
import java.util.ArrayList;
import java.util.List;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTest {
private static Person person = null;
private static List<Property> propertyList = new ArrayList<>();
public static void main(String[] args) throws Exception {
person = new Person(1, "Jhon");
propertyList.add(new Property(1, person, "Palace"));
propertyList.add(new Property(2, person, "Apartment"));
person.setPropertyList(propertyList);
jacksonTest();
//jsonbTest();
}
private static void jacksonTest()
throws Exception
{
String result = new ObjectMapper().writeValueAsString(person);
System.out.println("result: " + result);
}
private static void jsonbTest()
throws Exception
{
Jsonb jsonb = JsonbBuilder.create();
/**
* stackoverflow here
*/
System.out.println("jsonPerson with property: " + jsonb.toJson(person));
}
public static class Property extends BaseEntity {
private Person person;
private String propertyName;
public Property(int id, Person person, String propertyName) {
super();
setId(id);
this.person = person;
this.propertyName = propertyName;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
}
public static class Person extends BaseEntity {
public Person() {
super();
}
public Person(int id, String name) {
super();
setId(id);
this.name = name;
}
private String name;
private List<Property> propertyList = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Property> getPropertyList() {
return propertyList;
}
public void setPropertyList(List<Property> propertyList) {
this.propertyList = propertyList;
}
}
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static abstract class BaseEntity {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
Jackson output:
result: {"id":1,"name":"Jhon","propertyList":[{"id":1,"person":1,"propertyName":"Palace"},{"id":2,"person":1,"propertyName":"Apartment"}]}
hello am new to jackson and am trying to convert a text file into JSON but am having problem with my text file I dont know in what format the details of text file should be below is my code
ERROR : org.codehaus.jackson.map.JsonMappingException: Unrecognized field "Employee" (Class test.Employee), not marked as ignorable
at [Source: C:\Users\Ashwin Utchanah\Desktop\BIOGRID\jsonInput.txt; line: 3, column: 2]
text file : {"Employee":{"EmpID":1234,"name":"assd","designation":”programmer”,"salary":25000}}
Employee Class :
public class Employee {
private int empId;
private String name;
private String designation;
private String department;
private int salary;
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("************************************");
sb.append("\nempId: ").append(empId);
sb.append("\nname: ").append(name);
sb.append("\ndesignation: ").append(designation);
sb.append("\ndepartment: ").append(department);
sb.append("\nsalary: ").append(salary);
sb.append("\n************************************");
return sb.toString();
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
Main Class :
public class ObjectToJson {
public static void main(String [] args) {
ObjectMapper mapper = new ObjectMapper();
try {
File jsonInputFile = new File("C:\\Users\\Ashwin Utchanah\\Desktop\\BIOGRID\\jsonInput.txt");
Employee emp = mapper.readValue(jsonInputFile, Employee.class);
System.out.println(emp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The JSON you're trying to convert into a concrete object is not a valid one.
You can easily test this using a JSON validator like JSON lint.
https://jsonlint.com/
The problem occurs from the top level Employee field. Changing your input file to:
{
"EmpID": 1234,
"name": "assd",
"designation": "programmer",
"salary": 25000
}
Should fix your problem.
I have to create Java object from JSON string received in servlet
Below is the JSON
[{"name":"name","value":"Shital"},{"name":"email","value":"swankhade#gmail.com"},{"name":"contactno","value":"9920042776"},{"name":"Address","value":"a6 102 Elementa"}]
I tried to change the JSON that is by replacing [ by { and ] by } but it gives some other error.
My jackson code where I am getting exception is
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to Article
Enrole enrole = mapper.readValue(json, Enrole.class);
And the Enroll class is simple bean class with setter and getter
public class Enrole {
private String name;
private String email;
private long contactno;
private String address;
This is one of the way
try {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"name\",\"value\":\"Shital\"},{\"name\":\"email\",\"value\":\"swankhade#gmail.com\"},{\"name\":\"contactno\",\"value\":\"9920042776\"},{\"name\":\"Address\",\"value\":\"a6 102 Elementa\"}]";
KeyValue[] jsonObjArr = mapper.readValue(json, KeyValue[].class);
Enrole enrol = new Enrole();
for (int i = 0; i < jsonObjArr.length; i++) {
KeyValue keyVal = jsonObjArr[i];
if ("name".equals(keyVal.getName())) {
enrol.setName(keyVal.getValue());
}
if ("email".equals(keyVal.getName())) {
enrol.setEmail(keyVal.getValue());
}
if ("contactno".equals(keyVal.getName())) {
enrol.setContactno(Long.parseLong(keyVal.getValue()));
}
if ("address".equals(keyVal.getName())) {
enrol.setAddress(keyVal.getValue());
}
}
System.out.println(enrol.getName());
System.out.println(enrol.getContactno());
System.out.println(enrol.getAddress());
System.out.println(enrol.getEmail());
} catch (Exception e) {
System.out.println("Exception " + e);
}
Class with Key and Value :
class KeyValue {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Model Class
class Enrole {
private String name;
private String email;
private long contactno;
private String address;
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 long getContactno() {
return contactno;
}
public void setContactno(long contactno) {
this.contactno = contactno;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
When I use #JsonUnwrapped on nested field:
public class Person{
private int id;
#JsonUnwrapped
private Father father
//getters/setters
#Data
#AllArgsConstructor
private static class Father {
private String name;
private String surname;
}
And at the same time I use the #JsonCreator:
#JsonCreator // DESERIALIZATION: JSON -> POJO
public Person(...
#JsonProperty("name") String name,
#JsonProperty("surname") String surname) {
(...)
this.father = new Father(name, surname);
with Father being nested class.
I get the error:
Father` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creat
But when I remove the #JsonUnwrapped the field gets deserialised ok but is not flatten during serialisation.
How to assure that Father field will be serialised and deserialised flatten at the same time?
EDIT:
I paste full code:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class Person {
private int id;
private String firstName;
private String lastName;
private boolean active;
private Address address;
private String[] languages;
#JsonIgnore private boolean isTheKing;
#JsonUnwrapped // SERIALIZATIONL POJO -> JSON
private Father father;
#JsonCreator // DESERIALIZATION: JSON -> POJO
public Student(
#JsonProperty("id") int id,
#JsonProperty("firstName") String firstName,
#JsonProperty("lastName") String lastName,
#JsonProperty("active") boolean active,
#JsonProperty("address") Address address,
#JsonProperty("languages") String[] languages,
#JsonProperty("isTheKing") boolean isTheKing,
#JsonProperty("name") String name,
#JsonProperty("surname") String surname) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.active = active;
this.address = address;
this.languages = languages;
this.isTheKing = isTheKing;
this.father = new Father(name, surname);
}
public int getId() {
return id;
}
public void setId(int 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 boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String[] getLanguages() {
return languages;
}
public void setLanguages(String[] languages) {
this.languages = languages;
}
public Father getFather() {
return father;
}
public void setFather(Father father) {
this.father = father;
}
#Data
#AllArgsConstructor
static class Father {
private String name;
private String surname;
}
}
the following main method fails:
ObjectMapper mapper = new ObjectMapper();
Person myStudent =
mapper.readValue(new File("src/main/resources/data/rest/studentIN.json"), Person.class);
System.out.println(myStudent);
with error:
Exception in thread "main"
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot
construct instance of com.example.demo.Person$Father
(no Creators, like default construct, exist): cannot deserialize from
Object value (no delegate- or property-based Creator)
I use lombok:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
It should work for simple POJO model. Father class should be public:
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Person.Father father = new Person.Father();
father.setName("Wit");
father.setSurname("Pil");
Person person = new Person();
person.setId(1909);
person.setFather(father);
String json = mapper.writeValueAsString(person);
System.out.println(json);
System.out.println(mapper.readValue(json, Person.class));
}
}
class Person {
private int id;
#JsonUnwrapped
private Father father;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Father getFather() {
return father;
}
public void setFather(Father father) {
this.father = father;
}
#Override
public String toString() {
return "Person{" +
"id=" + id +
", father=" + father +
'}';
}
static class Father {
private String name;
private String surname;
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;
}
#Override
public String toString() {
return "Father{" +
"name='" + name + '\'' +
", surname='" + surname + '\'' +
'}';
}
}
}
Above code prints:
{
"id" : 1909,
"name" : "Wit",
"surname" : "Pil"
}
Person{id=1909, father=Father{name='Wit', surname='Pil'}}
I've tested it for many version since 2.6.7 and it works fine.