I am working on deserializing the below JSON:
{"self":"http://members.cs.com/rest/api/user?username=abc#cs.com",
"key":"abc#cs.com",
"name":"abc#cs.com",
"emailAddress":"abc#cs.com",
"displayName":"ABC",
"active":true,
"members":{"size":1,"items":[{"name":"member-users","self":"http://members.cs.com/rest/api/user?username=abc#cs.com"}]},
"expand":"members"}
I have created the following classes:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserList {
private String name;
private String emailAddress;
private String displayName;
private boolean active;
List<MemberName> members = new ArrayList<>();
#JsonCreator
public UserList(#JsonProperty("name") String name, #JsonProperty("emailAddress") String emailAddress, #JsonProperty("displayName") String displayName, #JsonProperty("active") boolean active, #JsonProperty("members") List<MemberName> members) {
this.name = name;
this.emailAddress = emailAddress;
this.displayName = displayName;
this.active = active;
this.members.addAll(groups);
}
//getters
}
#JsonIgnoreProperties(ignoreUnknown = true)
public class MemberName {
private String name;
#JsonCreator
public MemberName(#JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
When I don't give the members as a property the deserialization works fine and I can see the values for the name, displayName, active, emailAddress. The problem happens with the MemberName.
Could someone help with this?
This worked for me:
Class Items as below:
public class Items {
private String name;
private String self;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
}
Members class as below:
public class Members {
private int size;
private List<Items> items;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<Items> getItems() {
return items;
}
public void setItems(List<Items> items) {
this.items = items;
}
}
Data class as below:
public class Data {
private String self;
private String key;
private String name;
private String emailAddress;
private String displayName;
private boolean active;
private Members members;
private String expand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Members getMembers() {
return members;
}
public void setMembers(Members members) {
this.members = members;
}
public String getExpand() {
return expand;
}
public void setExpand(String expand) {
this.expand = expand;
}
}
The deserialization as below:
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String jsonString = "{\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\",\"key\": \"abc#cs.com\",\"name\": \"abc#cs.com\","
+ "\"emailAddress\": \"abc#cs.com\",\"displayName\": \"ABC\",\"active\": true,\"members\": {\"size\": 1,\"items\": [{"
+ "\"name\": \"member-users\",\"self\": \"http://members.cs.com/rest/api/user?username=abc#cs.com\" }]},\"expand\": \"members\"}";
ObjectMapper mapper = new ObjectMapper();
Data obj = mapper.readValue(jsonString,Data.class);
System.out.println(obj.getSelf());
System.out.println(obj.getKey());
System.out.println(obj.getName());
System.out.println(obj.getEmailAddress());
System.out.println(obj.getDisplayName());
System.out.println(obj.isActive());
System.out.println(obj.getMembers().getSize());
System.out.println(obj.getMembers().getItems().get(0).getName());
System.out.println(obj.getMembers().getItems().get(0).getSelf());
System.out.println(obj.getExpand());
}
Related
Customer entity
#Entity
#Table(name="Customer")
public class Customer {
#Id
#GeneratedValue
private Long cusId;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
#Column(name="address")
private String add;
#Column(name="tel")
private int tel;
#Column(name="email")
private String email;
#Column(name="userName")
private String username;
#Column(name="password")
private String password;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "customer")
#JsonManagedReference
private List<Complain> complain=new ArrayList<Complain>();
public Customer() {
super();
// TODO Auto-generated constructor stub
}
public Long getCusId() {
return cusId;
}
public void setCusId(Long cusId) {
this.cusId = cusId;
}
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 getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Complain> getComplain() {
return complain;
}
public void setComplain(List<Complain> complain) {
this.complain = complain;
}
}
Complain Entity
#Entity
#Table(name="Complain")
public class Complain {
#Id
#GeneratedValue
private Long id;
#Column(name="repfirst")
private String repfirst;
#Column(name="replast")
private String replast;
#Column(name="warranty")
private String warranty;
#Column(name="dop")
private String purDate;
#Column(name="Nomachine")
private String Nomachine;
#Column(name="Complain")
private String Complain;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="cus_id", referencedColumnName = "cusId")
#JsonBackReference
private Customer customer;
public Complain() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRepfirst() {
return repfirst;
}
public void setRepfirst(String repfirst) {
this.repfirst = repfirst;
}
public String getReplast() {
return replast;
}
public void setReplast(String replast) {
this.replast = replast;
}
public String getWarranty() {
return warranty;
}
public void setWarranty(String warranty) {
this.warranty = warranty;
}
public String getPurDate() {
return purDate;
}
public void setPurDate(String purDate) {
this.purDate = purDate;
}
public String getNomachine() {
return Nomachine;
}
public void setNomachine(String nomachine) {
Nomachine = nomachine;
}
public String getComplain() {
return Complain;
}
public void setComplain(String complain) {
Complain = complain;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
I want to pass data to the mysql database through the postman tool. How can I pass value for the foreign key column through the json query?
This is the method I have used in controller
#PostMapping(path="/",consumes="application/json",produces="application/json")
public void addComplain(#RequestBody Complain complain)
{
Integer id = complainService.getAllComplain().size()+1;
complain.setId(new Long(id));
complainService.createOrUpdateComplain(complain); }
After I send the request from the postman, all the data are saved except the foreign key. I think I missed something in mapping two tables.
This is my json query
{"complain":"No power",
"repfirst":"hi",
"replast":"all",
"warranty":"yes",
"purDate":"2020-02-29",
"nomachine":"6",
"tel":"46544654",
"Customer":[
{"cusId":"1"}
]
}
Database table image
Please help, Thanks in advance
{
"repfirst": "",
"replast": "",
"warranty": "",
"purDate" : "",
"Nomachine": "",
"Complain": "",
"cus_id": 1
}
That should work
"Customer":[
{"cusId":"1"}
]
This would work if you had Set<Customer> customers converted to an array in json, for example.
it's me again. so i have this javafx tableview which i have loaded dynamically with rows and columns from my database. it works out well but there's something i realized. two particular columns in the tableview switch their values. it happened once and when i cancelled the process and ran the program again, it didn't happen, then out of the blues, it happened again. i attached an image so you'd understand better. THANKS GUYS!!
below is the code that populates the tableview with Columns and rows from the database. i don't get any error when i run this.
public void buildData () {
String str = "SELECT * FROM EMPLOYEE_TABLE";
data = FXCollections.observableArrayList();
try {
ResultSet rs = DBaseUtils.dbaseExecuteQuery(str);
for(int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
String columnName = rs.getMetaData().getColumnName(i + 1);
TableColumn<Employee, String> column = new TableColumn<>(columnName);
column.setCellValueFactory(new PropertyValueFactory<>(columnName));
column.setCellFactory(TextFieldTableCell.<Employee>forTableColumn());
column.setOnEditCommit(new EventHandler<>() {
#Override
public void handle(TableColumn.CellEditEvent<Employee, String> event) {
TableColumn<Employee, String> col = event.getTableColumn();
int row = event.getTablePosition().getRow();
ObservableValue<String> observe = col.getCellObservableValue(row);
if (observe instanceof WritableValue) {
((WritableValue<String>) observe).setValue(event.getNewValue());
}
}
});
empTable.getColumns().addAll(column);
}
while(rs.next()) {
Employee emp = new Employee();
emp.setEmployeeId(rs.getString(1));
emp.setFirstname(rs.getString(2));
emp.setLastname(rs.getString(3));
emp.setSex(rs.getString(4));
emp.setEmail(rs.getString(5));
emp.setPhoneNumber(rs.getString(6));
emp.setAddress(rs.getString(7));
emp.setHireDate(rs.getString(8));
emp.setState(rs.getString(9));
emp.setSalary(rs.getString(10));
emp.setDepartment(rs.getString(11));
emp.setSsn(rs.getString(12));
data.add(emp);
}
empTable.setItems(data);
empTable.setEditable(true);
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error building data! ");
}
}
i also attached the model class, well... just in case.
notice the naming conventions for the Property methods, i had to use that because those were the exact names on my database. and since it PropertyValueFactory uses Reflection.
public class Employee {
private SimpleStringProperty employeeId;
private SimpleStringProperty firstname;
private SimpleStringProperty lastname;
private SimpleStringProperty sex;
private SimpleStringProperty email;
private SimpleStringProperty phoneNumber;
private SimpleStringProperty hireDate;
private SimpleStringProperty address;
private SimpleStringProperty state;
private StringProperty salary;
private SimpleStringProperty department;
private SimpleStringProperty ssn;
private long time;
public Employee() {
this.employeeId = new SimpleStringProperty();
this.firstname = new SimpleStringProperty();
this.lastname = new SimpleStringProperty();
this.sex = new SimpleStringProperty();
this.email = new SimpleStringProperty();
this.phoneNumber = new SimpleStringProperty();
this.hireDate = new SimpleStringProperty();
this.address = new SimpleStringProperty();
this.state = new SimpleStringProperty();
this.salary = new SimpleStringProperty();
this.department = new SimpleStringProperty();
this.ssn = new SimpleStringProperty();
}
public String getEmployeeId() {
return employeeId.get();
}
public void setEmployeeId(String id) {
this.employeeId.set(id);
}
public StringProperty EMPLOYEE_IDProperty() {
return employeeId;
}
public String getFirstName() {
return firstname.get();
}
public void setFirstname(String firstname) {
this.firstname.set(firstname);
}
public StringProperty FIRST_NAMEProperty() {
return firstname;
}
public String getLastName() { return lastname.get(); }
public void setLastname(String lastname) {
this.lastname.set(lastname);
}
public StringProperty LAST_NAMEProperty() {
return lastname;
}
public String getSex() {
return sex.get();
}
public void setSex(String sex) {
this.sex.set(sex);
}
public StringProperty SEXProperty() {
return sex;
}
public String getEmail() {
return email.get();
}
public void setEmail(String email) {
this.email.set(email);
}
public StringProperty EMAILProperty() {
return email;
}
public String getPhoneNumber() {
return phoneNumber.get();
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber.set(phoneNumber);
}
public StringProperty PHONE_NUMBERProperty() {
return phoneNumber;
}
public String getHireDate() {
return hireDate.get();
}
public void setHireDate(String date) {
this.hireDate.set(date);
}
public SimpleStringProperty HIRE_DATEProperty() {
return hireDate;
}
public String getAddress() {
return address.get();
}
public void setAddress(String address) {
this.address.set(address);
}
public StringProperty ADDRESSProperty() {
return address;
}
public String getState() {
return state.get();
}
Here's the image. notice the different values in the HIRE_DATE COLUMN AND ADDRESS COLUMN
So I am building a REST api using SpringDataRest both Get and Post are working but I don´t know whats wrong with the PUT.
This is the entity im using:
#Entity
#Table(name = "companies")
public class Company {
#Id
#Column(name="CompanyId", nullable=false, unique=true)
private String companyId;
#Column(name="Name", nullable=false)
private String name;
#Column(name="ContactName", nullable=false)
private String contactName;
#Column(name="ContactSurName")
private String contactSurname;
#Column(name="ContactEmail", nullable=false)
private String contactEmail;
#Column(name="ContactPhone")
private String contactPhone;
#Column(name="Enabled", nullable=false)
private String enabled;
#Column(name="Logo")
private String logo;
#Column(name = "CreationDate", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Column(name = "LastUpdateDate", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdateDate;
//Region Constructors
private Company(){}
public Company(String companyId, String name, String contactName, String contactSurname, String contactEmail, String contactPhone,
String enabled){
this.companyId = companyId;
this.name = name;
this.contactName = contactName;
this.contactSurname = contactSurname;
this.contactEmail = contactEmail;
this.contactPhone = contactPhone;
this.enabled = enabled;
this.creationDate = new Date();
this.lastUpdateDate = new Date();
}
//EndRegion
//Region Getters & Setters
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactSurname() {
return contactSurname;
}
public void setContactSurname(String contactSurname) {
this.contactSurname = contactSurname;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
//EndRegion
}
When I execute this request:
REQUEST
I get this response:
{
"cause": {
"cause": null,
"message": "No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream#1130374; line: 1, column: 0]"
},
"message": "Could not read an object of type class com.wipma.application.domain.Company from the request!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream#1130374; line: 1, column: 0]"
}
I can´t figure out whats wrong, I suspect its something related with some field mapping but cant sort it out.
Thanks in advance
I know this question has been brought up quite often, but so far I didn't really find an answer...
I am trying to use Android with GSON. I want to use a JSON String to fill a Gridview but I dont know how to access the nested objects.
The JSON File:
[{'ProductCategories':[
{
'name':'Cat1', 'Product Series':[
{
'name':'ProdSeries1', 'Description':'Lorem Ipsum Bla Bla','Products':[
{
'name':'Product1','key':'value','key':'...'
},
{
'name':'Product2','key':'value','key':'...'
},
]
}
]
},
]
}]
I made 4 classes:Products,ProductSeries,ProductCatalog and ProductCategory.
example:
public class ProductCatalog {
#SerializedName("ProductCategories")
#Expose
private List<ProductCategory> productCategories = null;
public List<ProductCategory> getProductCategories() {
return productCategories;
}
public void setProductCategories(List<ProductCategory> productCategories) {
this.productCategories = productCategories;
}
}
After that I parsed the JSON with gson:
Gson gson = new Gson();
Type type = new TypeToken<List<ProductCatalog>>(){}.getType();
List<ProductCatalog> productcatalog = gson.fromJson(JSONstring,type);
Now I have a parsed list of the JSON data but dont know how to work with the nested objects like 'Product1'. I thought the getters would help, but I cant access getProductCategories() in my activity. How can I do that?
If your using Gson means This will help you
public class MainClazz {
#SerializedName("ProductCategories")
#Expose
private List<ProductCategory> productCategories = null;
public List<ProductCategory> getProductCategories() {
return productCategories;
}
public void setProductCategories(List<ProductCategory> productCategories) {
this.productCategories = productCategories;
}
}
public class Product {
#SerializedName("name")
#Expose
private String name;
#SerializedName("key")
#Expose
private String key;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
public class ProductCategory {
#SerializedName("name")
#Expose
private String name;
#SerializedName("Product Series")
#Expose
private List<ProductSeries> productSeries = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ProductSeries> getProductSeries() {
return productSeries;
}
public void setProductSeries(List<ProductSeries> productSeries) {
this.productSeries = productSeries;
}
}
public class ProductSeries {
#SerializedName("name")
#Expose
private String name;
#SerializedName("Description")
#Expose
private String description;
#SerializedName("Products")
#Expose
private List<Product> products = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
I have a simple JSON statement which type is very per need. like this
{
actor:{name:"kumar",mbox:"kumar#gmail.com"}
verb :"completed"
}
or
{
actor:{name:["kumar","manish"],mbox:["kumar#gmail.com","manish#gmail.com"]}
verb :{
"id" : "http://adlnet.gov/expapi/verbs/completed",
"display" : {
"en-US" : "completed"
}
}
I am using using POJO class to map this json string and pojo class code is given bleow
#JsonProperty("actor")
Actor actor;
#JsonProperty("verb")
Verb objVerb;
#JsonProperty("verb")
String verb;
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
public Verb getObjVerb() {
return objVerb;
}
public void setObjVerb(Verb objVerb) {
this.objVerb = objVerb;
}
#JsonIgnore
public String getVerb() {
return verb;
}
#JsonIgnore
public void setVerb(String verb) {
this.verb = verb;
}
public static class Actor {
String objectType;
#JsonProperty("name")
ArrayList<String> listName;
#JsonProperty("name")
String name;
#JsonProperty("mbox")
ArrayList<String> listMbox;
#JsonProperty("mbox")
String mbox;
#JsonProperty("mbox_sha1sum")
ArrayList<String> Listmbox_sha1sum;
#JsonProperty("mbox_sha1sum")
String mbox_sha1sum;
#JsonProperty("openid")
String openid;
#JsonProperty("account")
Account account;
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public ArrayList<String> getListName() {
return listName;
}
public void setListName(ArrayList<String> listName) {
this.listName = listName;
}
#JsonIgnore
public String getName() {
return name;
}
#JsonIgnore
public void setName(String name) {
this.name = name;
}
public ArrayList<String> getListMbox() {
return listMbox;
}
public void setListMbox(ArrayList<String> listMbox) {
this.listMbox = listMbox;
}
#JsonIgnore
public String getMbox() {
return mbox;
}
#JsonIgnore
public void setMbox(String mbox) {
this.mbox = mbox;
}
public ArrayList<String> getListmbox_sha1sum() {
return Listmbox_sha1sum;
}
public void setListmbox_sha1sum(ArrayList<String> listmbox_sha1sum) {
Listmbox_sha1sum = listmbox_sha1sum;
}
#JsonIgnore
public String getMbox_sha1sum() {
return mbox_sha1sum;
}
#JsonIgnore
public void setMbox_sha1sum(String mbox_sha1sum) {
this.mbox_sha1sum = mbox_sha1sum;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public static class Account {
#JsonProperty("homePage")
String homePage;
#JsonProperty("name")
String name;
public String getHomePage() {
return homePage;
}
public void setHomePage(String homePage) {
this.homePage = homePage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Verb {
String id;
Map<String,String> display;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, String> getDisplay() {
return display;
}
public void setDisplay(Map<String, String> display) {
this.display = display;
}
}
I am using jaxb and jakson. I am implementing the webservice to handle the json statement
so I use the bean class to map with json. But when I use to map this json then it gives the following exceptions
org.codehaus.jackson.map.JsonMappingException : property with the name "mbox" have two entry.
Define a proper bean structure so it directly mapped to the beans class
Try to leave only #JsonProperty("mbox") ArrayList<String> listMbox; field (don't need #JsonProperty("mbox")
String mbox;)
and add Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY=true to Jackson object mapper config.
So in deserialization it will be able to get as both array and single element.
you can use gson.
class cls = gson.fromJson(jsonString, clazz);
here jsonString can be stringified java script object. gson.fromJson method can map your java script key to java property.