Below is my JSON, how to parse it using jaxb, note the depth and key of categories would change
{
"categories":{
"categoryHierarchy":[
{
"hierarchy":{
"SDG--1513417390":{
"SD-1501363638":{
"D-HS-MM4":{
"CL-HS-MM4-DEFAULT":{
"C-HS-MM4-MM0203":{
}
}
}
}
}
},
"precedence":1
}
]
}
}
After trying multiple things I was able to parse the recursive category structure.
package com.example;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pearson.aem.aemcore.pim.dto.com.example.Example;
class Parser{
private transient static ObjectMapper jsonMapper;
public static void main (String [] args) throws IOException
{
jsonMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String response = "{\"categoryHierarchy\":[{\"hierarchy\":{\"SDG--1513417390\":{\"SD-1501363638\":{\"D-HS-MM4\":{\"CL-HS-MM4-DEFAULT\":{\"C-HS-MM4-MM0203\":{}}}}}},\"precedence\":1}]}";
InputStream stream = new ByteArrayInputStream(response.getBytes());
Example ex = unmarshalJson(stream, Example.class);
System.out.println(ex.getCategoryHierarchy().get(0).getHierarchy1().getAdditionalProperties());
//System.out.println(ex.getCategoryHierarchy().get(0).getHierarchy().getAdditionalProperties().get("SDG--1513417390").keySet.iterator().next());
}
public static <T> T unmarshalJson(final InputStream result, final Class<T> declaredType) throws IOException
{
return (T) jsonMapper.readValue(result, declaredType);
}
}
----------------
package com.example;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.pearson.aem.aemcore.pim.dto.CategoryElementDTO;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Example
{
#XmlElement(
name = "categoryHierarchy")
private List<CategoryHierarchy> categoryHierarchy;
#XmlElement(
name = "relatedCategories")
private Map<String, CategoryElementDTO> relatedCategories;
public List<CategoryHierarchy> getCategoryHierarchy()
{
return categoryHierarchy;
}
public void setCategoryHierarchy(List<CategoryHierarchy> categoryHierarchy)
{
this.categoryHierarchy = categoryHierarchy;
}
public Map<String, CategoryElementDTO> getRelatedCategories()
{
return relatedCategories;
}
public void setRelatedCategories(Map<String, CategoryElementDTO> relatedCategories)
{
this.relatedCategories = relatedCategories;
}
}
------------
package com.example;
public class CategoryHierarchy
{
private Hierarchy hierarchy;
private Integer precedence;
public Hierarchy getHierarchy()
{
return hierarchy;
}
public void setHierarchy(Hierarchy hierarchy)
{
this.hierarchy = hierarchy;
}
public Integer getPrecedence()
{
return precedence;
}
public void setPrecedence(Integer precedence)
{
this.precedence = precedence;
}
}
---------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Hierarchy
{
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties()
{
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value)
{
this.additionalProperties.put(name, value);
}
}
Related
Good morning I have a small query, I am doing a small web service rest with spring boot, the issue is that it is working fine and everything else, as I am doing as follows, receives a parameter and returns a response based on a Stored Procedue in the database:
But now I have changed the request, and it is including header and body, like the following:
{
"ValidateClient": {
"Header": {
"country": "VE",
"lang": "ES",
"entity": "TMVE",
"system": "76",
"subsystem": "APP",
"operation": "ValidateClient",
"timestamp": "2019-10-23T08:48:08.474Z",
"msgType": "REQUEST"
},
"Body": {
"validateClientRequest": {
"movil": "04141734272"
}
}
}
}
Which when executing it gives me an answer of not found the mobile, it is a default response when it cannot read the mobile parameter or it is sent empty
My Code
Main Class
package com.app.validate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ValidateClientApp {
public static void main(String[] args) {
SpringApplication.run(ValidateClientApp.class, args);
}
}
Controller
package com.app.validate.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.validate.dao.ValidateClientAppRepository;
import com.app.validate.entity.DriverBonificados;
import com.app.validate.entity.ResponseVo;
#RestController
public class ValidateClientAppController {
#Autowired
private ValidateClientAppRepository dao;
#PostMapping(value = "/ValidateClientApp",consumes = "application/json",produces="application/json")
public ResponseVo ValidateClient(#RequestBody DriverBonificados driver) {
//System.out.println(driver.getMovil());
return dao.validarClienteBonifiado(driver.getMovil());
}
}
Dao
package com.app.validate.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.app.validate.entity.DriverBonificados;
import com.app.validate.entity.ResponseVo;
#Repository
public interface ValidateClientAppRepository extends JpaRepository<DriverBonificados, Integer> {
#Query(nativeQuery = true,value = "call ValidacionClienteBonificado(:movil)")
ResponseVo validarClienteBonifiado(#Param("movil") String pMovil);
}
Entity
package com.app.validate.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="DriverBonificados")
public class DriverBonificados {
#Id
private int id;
private String movil;
private String contador;
private Date fecha_driver;
private Date fecha_alta;
private Date fecha_fin;
private Date codigo_transaccion;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMovil() {
return movil;
}
public void setMovil(String movil) {
this.movil = movil;
}
public String getContador() {
return contador;
}
public void setContador(String contador) {
this.contador = contador;
}
public Date getFecha_driver() {
return fecha_driver;
}
public void setFecha_driver(Date fecha_driver) {
this.fecha_driver = fecha_driver;
}
public Date getFecha_alta() {
return fecha_alta;
}
public void setFecha_alta(Date fecha_alta) {
this.fecha_alta = fecha_alta;
}
public Date getFecha_fin() {
return fecha_fin;
}
public void setFecha_fin(Date fecha_fin) {
this.fecha_fin = fecha_fin;
}
public Date getCodigo_transaccion() {
return codigo_transaccion;
}
public void setCodigo_transaccion(Date codigo_transaccion) {
this.codigo_transaccion = codigo_transaccion;
}
}
Interface Response Stored Procedue
package com.app.validate.entity;
public interface ResponseVo {
String getCode();
String getResult();
}
How could you do to read the Json with header and body? I'm new to spring boot
UPDATE
According to what Silverfang said, I created the classes said by him, but I get an error that I describe next:
BodyRequest.java
public class BodyRequest {
private String validateClientRequest;
private String movil;
public String getValidateClientRequest() {
return validateClientRequest;
}
public void setValidateClientRequest(String validateClientRequest) {
this.validateClientRequest = validateClientRequest;
}
public String getMovil() {
return movil;
}
public void setMovil(String movil) {
this.movil = movil;
}
}
HeaderRequest.java
package com.app.validate.controller;
import java.util.Date;
public class HeaderRequest {
private String country;
private String lang;
private String entity;
private String system;
private String subsystem;
private String operation;
private Date timestamp;
private String msgType;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getEntity() {
return entity;
}
public void setEntity(String entity) {
this.entity = entity;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
public String getSubsystem() {
return subsystem;
}
public void setSubsystem(String subsystem) {
this.subsystem = subsystem;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
}
RequestBodyDemo.java
package com.app.validate.controller;
public class RequestBodyDemo {
private ValidateClientRequest ValidateClient;
public ValidateClientRequest getValidateClient() {
return ValidateClient;
}
public void setValidateClient(ValidateClientRequest validateClient) {
ValidateClient = validateClient;
}
}
ValidateClientRequest
package com.app.validate.controller;
public class ValidateClientRequest {
private BodyRequest Body;
private HeaderRequest Header;
public BodyRequest getBody() {
return Body;
}
public void setBody(BodyRequest body) {
Body = body;
}
public HeaderRequest getHeader() {
return Header;
}
public void setHeader(HeaderRequest header) {
Header = header;
}
}
My Controller (Update)
package com.app.validate.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.validate.dao.ValidateClientAppRepository;
import com.app.validate.entity.DriverBonificados;
import com.app.validate.entity.ResponseVo;
#RestController
public class ValidateClientAppController {
#Autowired
private ValidateClientAppRepository dao;
#PostMapping(value = "/ValidateClientApp",consumes = "application/json",produces="application/json")
public ResponseVo ValidateClient(#RequestBody RequestBodyDemo req) {
System.out.println(req.getValidateClient().getBody().getMovil());
return dao.validarClienteBonifiado(req.getValidateClient().getBody().getMovil());
}
}
The error I get:
From what I understand you have changed the request format and now want the same request body to work for the same controller.
I think you were trying to add the fields to the header. What you are doing here is not the right way to do it. It should goes to header section rather than in the body section of the Postman app. But doing so, you will have to specify these header separately as these are custom headers which will be a lot of work.
Answer to your question
Going by what you were trying to do. Since now you have changed the request body. You will have to make changes in the controller class too. Now it will require three classes If you want to do it in a modular way.
The first class will be BodyRequest.java
private string validateClientRequest;
private string movil;
The next class will be HeaderRequest.java
private string country;
private string lang;
private string entity;
private string system;
private string subsystem;
private string operation;
private Date timestamp;
private string msgType;
Next class will be ValidateClientRequest.java
private HeaderRequest Header;
private BodyRequest Body;
Now for the RequestBodyDemo class;
private ValidateClientRequest ValidateClient;
Note : Use appropriate Getter and setter along with #JsonProperty if you are masking the input request data.
Once these things are done. In your controller Instead of using Entity in #RequestBody Use the class RequestBodyDemo. Once that is done. Just try printing the values just to check whether you are getting them right or not. Then use getter for fetching any value that you need.
Edit :
public ResponseVo ValidateClient(#RequestBody RequestBodyDemo req) {
System.out.println(req.getValidateClient().getBodyrequest().getMovil());
return dao.validarClienteBonifiado(req.getValidateClient().getBodyrequest().getMovil());
}
Note : Use appropriate getter method here.
I've got the following task:
I need to Produce a Spring Boot REST API that reads in data from a JSON file and allows the user to filter by colour.
The URL should look similar to: http://localhost:8080/cars?colour=red
The input data is in the included JSON file (cars.json)
It is of the form:
{
"cars": [
{
"brand": "ford",
"model": "fiesta",
"fuel": "petrol",
"doors": 5,
"colour": "blue"
}
]
}
I'm struggling to structurize JSON parsing classes properly, and here's my code
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.challenge.esure.service.MainService;
#RestController
public class MainController {
private final MainService mainService;
#Autowired
public MainController(MainService mainService) {
this.mainService = mainService;
}
#GetMapping("/all")
public List<Cars> getAll() throws IOException {
return mainService.getAllRecords();
}
#GetMapping("/cars?colour={colour}")
public Cars getColour(#PathVariable("colour") String colour) throws IOException, ColourNotFoundException {
return mainService.getCarColour(colour);
}
}
//Service:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.challenge.esure.domain.CarDetails;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#Service
public class MainService {
public List<Cars> getData() throws IOException{
Resource resource = new ClassPathResource("cars.json");
InputStream input = resource.getInputStream();
File file = resource.getFile();
ObjectMapper objectMapper = new ObjectMapper();
List<Cars> car = Arrays.asList(objectMapper.readValue(file, Cars[].class));
return car.stream().collect(Collectors.toList());
}
public List<Cars> getAllRecords() throws IOException {
return getData();
}
public Cars getCarColour(String colour) throws ColourNotFoundException, IOException {
return getData().stream()
.filter(Cars -> Cars.getColour().equals(colour))
.findAny()
.orElseThrow(() -> new ColourNotFoundException("We don't have cars with that colour"));
}
}
// Domain
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Cars {
private ArrayList<Object> cars;
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
public Cars() {
}
public Cars(ArrayList<Object> cars, String brand, String model, String fuel, Integer doors, String colour) {
this.cars = cars;
this.brand = brand;
this.model = model;
this.fuel = fuel;
this.doors = doors;
this.colour = colour;
}
public ArrayList<Object> getCars() {
return cars;
}
public void setCars(ArrayList<Object> cars) {
this.cars = cars;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel;
}
public Integer getDoors() {
return doors;
}
public void setDoors(Integer doors) {
this.doors = doors;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
//Exception
public class ColourNotFoundException extends Exception {
public ColourNotFoundException(String what) {
super(what);
}
}
You can use the below data structure
#JsonIgnoreProperties(ignoreUnknown = true)
public class CarResponse {
List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
#Override
public String toString() {
return "CarResponse{" +
"cars=" + cars +
'}';
}
}
public class Car {
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
}
CarResponse carResponse= objectMapper.readValue(jsonString, CarResponse.class);
I have created a Spring Boot REST API with inbuilt Apache Derby database. It worked fine. Now I have to integrate it with MySQL. I have updated POM.XML and configured the driver.
Expense.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "vendor")
public class Expense {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String vendorId;
#Column
private String vendorName;
#Column
private int vendorPhone;
#Column
private int vendorBalance;
#Column
private int vendorChequeAmount;
public String getVendorId() {
return vendorId;
}
public void setVendorId(String vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}
public int getVendorPhone() {
return vendorPhone;
}
public void setVendorPhone(int vendorPhone) {
this.vendorPhone = vendorPhone;
}
public int getVendorBalance() {
return vendorBalance;
}
public void setVendorBalance(int vendorBalance) {
this.vendorBalance = vendorBalance;
}
public int getVendorChequeAmount() {
return vendorChequeAmount;
}
public void setVendorChequeAmount(int vendorChequeAmount) {
this.vendorChequeAmount = vendorChequeAmount;
}
public Expense(String vendorId, String vendorName, int vendorPhone, int vendorBalance, int vendorChequeAmount) {
super();
this.vendorId = vendorId;
this.vendorName = vendorName;
this.vendorPhone = vendorPhone;
this.vendorBalance = vendorBalance;
this.vendorChequeAmount = vendorChequeAmount;
}
application.properties
server.port = 8087
server.contextPath=/expense-tracker
spring.datasource.url=jdbc:mysql://localhost:3306/web_customer_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudent
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
Please click for the MySQL details
When I run using Postman, I am getting 404 error. Something is wrong with MySQL configuration. Please help to identify it. Thanks
[EDIT]
ExpenseController.Java
package com.shef.expensetracker.expense;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping("/vendors")
public class ExpenseController {
#Autowired
private ExpenseService expenseService;
#GetMapping
public List<Expense> getAllExpenses(){
return expenseService.findAll();
}
#GetMapping(path = {"/{vendorId}"})
public Expense getExpense(#PathVariable String vendorId){
return expenseService.getExpenseById(vendorId);
}
#PostMapping
public void addExpense(#RequestBody Expense expense){
expenseService.addExpense(expense);
}
#PutMapping(path = {"/{vendorId}"})
public void updateExpense(#RequestBody Expense expense, #PathVariable String vendorId){
expenseService.updateExpense(expense,vendorId );
}
#DeleteMapping(path = {"/{vendorId}"})
public void deleteExpense( #PathVariable String vendorId){
expenseService.deleteExpense(vendorId );
}
}
ExpenseService.Java
package com.shef.expensetracker.expense;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class ExpenseService {
#Autowired
private ExpenseRepository expenseRepository;
/*private List<Expense> expenses = new ArrayList<>(
Arrays.asList(new Expense("1","Chicken", 1234, 500, 100),
new Expense("2","Mutton", 1234, 600, 100),
new Expense("3","Beef", 1234, 700, 100)
));*/
public List<Expense> findAll(){
List<Expense> expenses = new ArrayList<>();
expenseRepository.findAll().forEach(expenses::add);
return expenses;
}
public void addExpense(Expense expense) {
//expenses.add(expense);
expenseRepository.save(expense);
}
public Expense getExpenseById(String vendorId){
return expenseRepository.findOne(vendorId);
}
public void updateExpense(Expense expense, String vendorId) {
// TODO Auto-generated method stub
expenseRepository.save(expense);
}
public void deleteExpense(String vendorId) {
expenseRepository.delete(vendorId);
}
}
ExpenseTrackerApplication.Java
package com.shef.expensetracker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ExpenseTrackerApplication {
public static void main(String[] args) {
SpringApplication.run(ExpenseTrackerApplication.class, args);
}
}
This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 7 years ago.
I am new to JavaFX and I have been trying to implement this code for displaying data from MySQL database in a TableView. The problem is that when I run the code I get blank rows and I don't know why.
Here is my code for the class:
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
public class FXMLPatientsMasterController implements Initializable {
/*
mysql connection variables
*/
Connection conn=null;
PreparedStatement pat=null;
ResultSet rs=null;
private ObservableList<PatientDetails> patients;
#FXML
private TableView Table_Patients;
#FXML
private TableColumn patientID;
#FXML
private TableColumn Name;
#FXML
private TableColumn Surname;
#FXML
private TableColumn pnationalID;
#FXML
private TableColumn psex;
#FXML
private TableColumn pDOB;
// Some code here
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
conn = PMS263MySqlConnection.ConnectDB();
try {
patients = FXCollections.observableArrayList();
rs = conn.createStatement().executeQuery("select * from patients");
while (rs.next()) {
patients.add(new PatientDetails(rs.getInt("PatientId"),
rs.getString("fName"), rs.getString("Surname"), rs.getString("National_ID"), rs.getString("Sex"), rs.getString("DOB")));
}
patientID.setCellValueFactory(new PropertyValueFactory("PatientId"));
Name.setCellValueFactory(new PropertyValueFactory("fName"));
Surname.setCellValueFactory(new PropertyValueFactory("Surname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("National_ID"));
psex.setCellValueFactory(new PropertyValueFactory("Sex"));
pDOB.setCellValueFactory(new PropertyValueFactory("DOB"));
Table_Patients.setItems(null);
Table_Patients.setItems(patients);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error on Building Data");
}
}
public static class PatientDetails {
private final SimpleIntegerProperty Patientid;
private final StringProperty Pname;
private final StringProperty Psurname;
private final StringProperty Pnationalid;
private final StringProperty Psex;
private final StringProperty Pdob;
private PatientDetails(int patientid, String pname, String psurname, String pnationalid, String psex, String pdob) {
this.Patientid = new SimpleIntegerProperty(patientid);
this.Pname = new SimpleStringProperty(pname);
this.Psurname = new SimpleStringProperty(psurname);
this.Pnationalid = new SimpleStringProperty(pnationalid);
this.Psex= new SimpleStringProperty(psex);
this.Pdob = new SimpleStringProperty(pdob);
}
public SimpleIntegerProperty patientidProperty() {
return Patientid ;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexPsexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}
}
}
Assuming your database query works, you the property names wrong:
If the property "getter" is named myNameProperty() you need to use new PropertyValueFactory("myName").
Either the property "getters" need to be renamed or the strings used with the value factories:
patientID.setCellValueFactory(new PropertyValueFactory("patientId"));
Name.setCellValueFactory(new PropertyValueFactory("pname"));
Surname.setCellValueFactory(new PropertyValueFactory("psurname"));
pnationalID.setCellValueFactory(new PropertyValueFactory("pnationalid"));
psex.setCellValueFactory(new PropertyValueFactory("psex"));
pDOB.setCellValueFactory(new PropertyValueFactory("pdob"));
...
public SimpleIntegerProperty patientIdProperty() {
return Patientid;
}
public StringProperty pnameProperty() {
return Pname;
}
public StringProperty psurnameProperty() {
return Psurname;
}
public StringProperty pnationalidProperty() {
return Pnationalid;
}
public StringProperty psexProperty() {
return Psex;
}
public StringProperty pdobProperty() {
return Pdob;
}
I have the following java class
#XmlRootElement
#XmlSeeAlso(DataClass.class)
public static class EnvelopeClass<T> {
#XmlElement
public String version;
#XmlElement
public T data;
EnvelopeClass() {
}
EnvelopeClass(String version, T data) {
this.version = version;
this.data = data;
}
}
#XmlRootElement
public static class DataClass {
#XmlElement
public String name;
DataClass() {
}
DataClass(String name) {
this.name = name;
}
}
I'm creating its instance and marshaling it to json
EnvelopeClass<DataClass> dataClassEnvelopeClass = new EnvelopeClass<DataClass>("1.0", new DataClass("myName"));
I have next result:
{"version":"1.0","data":{"#type":"dataClass","name":"myName"}}
I do not want to have type type information in the json "#type":"dataClass", in other words I want to have next result:
{"version":"1.0","data":{"name":"myName"}}
Exactly this result I have when EnvelopeClass doesn't have Generics.
Is there a way to do this?
To get the desired behaviour, you can use #XmlAnyElement on the data property instead of #XmlElement. For the #XmlAnyElement property the value will correspond to a class with the matching #XmlRootElement annotation.
EnvelopeClass
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
#XmlRootElement
#XmlSeeAlso(DataClass.class)
public class EnvelopeClass<T> {
#XmlElement
public String version;
#XmlAnyElement
public T data;
EnvelopeClass() {
}
EnvelopeClass(String version, T data) {
this.version = version;
this.data = data;
}
}
DataClass
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="data")
public class DataClass {
#XmlElement
public String name;
DataClass() {
}
DataClass(String name) {
this.name = name;
}
}
Demo
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(EnvelopeClass.class);
DataClass data = new DataClass("myName");
EnvelopeClass envelope = new EnvelopeClass<DataClass>("1.0", data);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(envelope, System.out);
}
}