My Requirement:
I have a JSON request in a table column which is like below.
{
"customerData": [{ "primaryData":[ {
"HNo": "8-10-2",
"APTNM": "SRSENCLAVE",
"STRT": "MGCLNY"
}],
"officeData":{
"ADDR": "1/7-25",
"STRT": "FINDIST",
"LM": "JBE"
},
"ContactData": {
"PHNO":"XXXXXXXXX",
"ZIP":"XXXXXX",
"MAILCD": "XXXX"},
}
]}
I need to read it from DB and map the JSON values into three different class properties.i.e. PrimaryData.java. OfficeData.java,ContactData.java.
I'm able to successfully read the request from DB but struck on how to map the values to properties in my three POJO classes. I tried using faster xml, google Gson, org.json but I could not get it well. Can someone give me an idea or part of code snippet?
How I'm trying to achieve above (not sure if this approach is correct at all)
List<Map<String, PrimaryData>> cxData = new ArrayList<Map<String,PrimaryData>>();
JSONObject jSONObject = new JSONObject(query.getResultList().get(0).toString());
JSONArray jsonArray = jSONObject.getJSONArray("customerData");
int length = jsonArray.length();
for (int i=0; i<length; i++)
{
// FOR EACH ENTRY
JSONObject OneEntry = jsonArray.getJSONObject(i);
int OneEntrySize = OneEntry.length();
JSONArray EntKey = OneEntry.names();
Map<String, PrimaryData> map = new HashMap<String, PrimaryData>();
for (int j=0; j<OneEntrySize;j++)
{ // FOR EACH ITEM IN AN ENTRY
String key = EntKey.getString(j);
PrimaryData val = (PrimaryData)OneEntry.opt(key);;--unable to cast (can not cast JsonArray to PrimaryData)
map.put(key, val);
}
cxData.add(map);
}
With GSON
public class Data {
#SerializedName("customerData") #Expose private List<CustomerData> customerData = null;
}
public class CustomerData {
#SerializedName("primaryData") #Expose private List<PrimaryData> primaryData = null;
#SerializedName("officeData") #Expose private OfficeData officeData;
#SerializedName("ContactData") #Expose private ContactData contactData;
}
public class PrimaryData {
#SerializedName("HNo") #Expose private String hNo;
#SerializedName("APTNM") #Expose private String aPTNM;
#SerializedName("STRT") #Expose private String sTRT;
}
public class OfficeData {
#SerializedName("ADDR") #Expose private String aDDR;
#SerializedName("STRT") #Expose private String sTRT;
#SerializedName("LM") #Expose private String lM;
}
public class ContactData {
#SerializedName("PHNO") #Expose private String pHNO;
#SerializedName("ZIP") #Expose private String zIP;
#SerializedName("MAILCD") #Expose private String mAILCD;
}
Gson gson = new Gson();
Data data = gson.fromJson(dataJSON, Data.class);
Related
Im trying to access some list items from a json response using retrofit but cant seem to be able to access using get method. The ListQuotes seems to be saying null
#JsonPropertyOrder({
"page",
"last_page",
"quotes"
})
public class ListQuoteResponse {
#JsonProperty("quotes")
private List<Quote> quotes = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public ListQuoteResponse() {
}
#JsonProperty("quotes")
public List<Quote> getQuotes() {
return quotes;
}
#JsonProperty("quotes")
public void setQuotes(List<Quote> quotes) {
this.quotes = quotes;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
But when I open the Quote class I am unable to access any of the properties
public class Quote {
#JsonProperty("id")
private Integer id;
#JsonProperty("dialogue")
private Boolean dialogue;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public Quote() {
}
#JsonProperty("id")
public Integer getId() {
return id;
}
#JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("dialogue")
public Boolean getDialogue() {
return dialogue;
}
#JsonProperty("dialogue")
public void setDialogue(Boolean dialogue) {
this.dialogue = dialogue;
}
I tried using
listQuoteBodyResponse.body().getQuotes() but that only returned random numbers and when I tried using the Quote class for the response directly like
QuoteResponse.body.getDialogue() its just returning null
I'm building an angular springboot application but I find so many approaches to do this some of which I honestly do not understand.
how can I store 1 or more images at a time and retrieve them.
You can use #Lob to store Images or Any Files in the Database. The following example shows a simple implementation of this approach
#Entity
#Table(name = "file")
public class File {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "uuid")
private String uuid;
#Column(name = "content_type")
private String contentType;
#Column(name = "extension")
private String extension;
#Lob
#Column(name = "content", columnDefinition = "LONGBLOB")
private byte[] content;
}
#Service
public class FileService {
private final FileRepository repository;
#Autowired
public FileService(FileRepository repository) {
this.repository = repository;
}
#Transactional
public StreamingResponseBody download(Long id, HttpServletResponse response) {
final File file = repository.findById(id).orElseThrow(NotFoundException::new);
return outputStream -> {
String fileName = (file.getUuid() + file.getExtension()).trim();
response.setContentType(file.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
outputStream.write(file.getContent());
outputStream.flush();
};
}
public FileDto create(MultipartFile multipartFile, boolean general) {
String fileName = multipartFile.getOriginalFilename();
String fileExtension = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf('.'));
String uuid = UUID.randomUUID().toString();
UserDto user = contextUtils.getPrincipal();
File file = new File();
file.setUuid(uuid);
file.setContentType(multipartFile.getContentType());
file.setExtension(fileExtension);
file.setGeneral(general);
file.setContent(multipartFile.getBytes());
file.setId(repository.save(file).getId());
return file;
}
}
This is my code of my class which gets the json response in "resp".
public class Caller extends Thread {
public CallSoap cs;
public String resp, Blood_Group, City;
ClassObj object;
Gson gson = new GsonBuilder().create();
public void run() {
try {
cs = new CallSoap();
resp = cs.CallGetDonorList(Blood_Group, City);
object = gson.fromJson(resp,ClassObj.class);
int a = 0;
}catch(Exception ex)
{
MainActivity.rslt=ex.toString();
}
}
}
resp has value like this:
[{
"Donor_Id":1,
"Donor_Name":"Rakesh",
"Donor_ContactNo":9044234578,
"Blood_Group":"A+",
"City":"Lucknow"},
{....}
]
and I have created a class to serialize these values as:
import com.google.gson.annotations.SerializedName;
public class ClassObj {
#SerializedName("Donor_Id")
private int Donor_Id;
#SerializedName("Donor_Name")
private String Donor_Name;
#SerializedName("Donor_ContactNo")
private String Donor_ContactNo;
#SerializedName("Blood_Group")
private String Blood_Group;
#SerializedName("City")
private String City;
}
You're trying to deserialize an array of donor objects, not just a single one. As such, you'll need to specify the type correctly:
//declaration
ClassObj[] objects;
//deserialization
objects = gson.fromJson(resp,ClassObj[].class);
I would also strongly consider naming your classes and variables appropriately, i.e. ClassObj could be Donor and objects could be donors.
I am building on Java FX application 3 weeks now and i have a problem i search things about that over the internet but i can't find the solution. I have to Populate Data on rows in a tableview i am getting data from database but i can't put it in the table i have this code that i use in order to take the data from Database.
public ObservableList<ObservableList> GetCustomerData(){
ObservableList<ObservableList> Data = FXCollections.observableArrayList();
try{
ConnectToDB();
DBStatement = DBConnection.createStatement();
DataRetrive = DBStatement.executeQuery("SELECT * FROM Customer");
while (DataRetrive.next()){
ObservableList<String> Row = FXCollections.observableArrayList();
Row.add(String.valueOf(DataRetrive.getInt(1)));
Row.add(DataRetrive.getString(2));
Row.add(DataRetrive.getString(3));
Row.add(DataRetrive.getString(4));
Row.add(DataRetrive.getString(5));
Row.add(DataRetrive.getString(6));
Row.add(DataRetrive.getString(7));
Row.add(DataRetrive.getString(8));
Row.add(DataRetrive.getString(9));
Data.add(Row);
}
CloseDB();
}catch(SQLException e){
e.printStackTrace();
}
return Data;
}
How can I add Data in table cells from this ObservableList?
It is good practice to have a separate class to CRUD operations:
public abstract class CustomerDML {
public static final String TABLE_NAME = "Customer";
QueryClass qc = new QueryClass();
public ObservableList<Map> getCustomerData() {
ObservableList<Map> productList = FXCollections.observableArrayList();
try {
qc.setPs(qc.getConn().prepareStatement("SELECT * FROM " + TABLE_NAME));
qc.setRs(qc.getPs().executeQuery());
while (qc.getRs().next()) {
Map<String, String> product = new HashMap<>();
product.put("cus_id", String.valueOf(qc.getRs().getInt("cus_id")));
product.put("name", qc.getRs().getString("name"));
product.put("age", String.valueOf(qc.getRs().getInt("age")));
product.put("telephone", qc.getRs().getString("telephone"));
productList.add(product);
}
return customerList;
} catch (SQLException ex) {
return null;
}
}
You can implement your QueryClass like below :
public class QueryClass {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
//private String query;
public QueryClass() {
conn = DBConnectionClass.myConnection();
}
//getters and setters
...
Lets assume the we have injected something like below to your controller from your fxml:
public class Customer_fxmlController extends CustomerDML implements Initializable {
#FXML
private TableView<Map> cusTable;
#FXML
private TableColumn idCol;
#FXML
private TableColumn nameCol;
#FXML
private TableColumn ageCol;
#FXML
private TableColumn telCol;
...
public void loadCustomers() {
idCol.setCellValueFactory(new MapValueFactory("cus_id"));
nameCol.setCellValueFactory(new MapValueFactory("name"));
ageCol.setCellValueFactory(new MapValueFactory("age"));
telCol.setCellValueFactory(new MapValueFactory("telephone"));
cusTable.setItems(getCustomerData());//Which returns a ObservableList<Map>
}
I am trying to get the user's friends list from Facebook.
The problem seems to be the Javabean...
FBUser fbuser = new Gson().fromJson(jsonStr, FBUser.class);
public class FBUser implements Serializable {
private static final long serialVersionUID = -3154429420153433117L;
private String id;
private String name;
private String email;
private Friends friendsList = new Friends();
private FBUser() { }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 List<Data> getFriendsList() {
return friendsList.getData();
}
public static class Friends implements Serializable {
private static final long serialVersionUID = 6991758772193514527L;
private List<Data> data;
private Friends() { }
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public class Paging implements Serializable {
private static final long serialVersionUID = 1689816298710621080L;
private String next;
private Paging() { }
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
}
}
public class Data implements Serializable {
private static final long serialVersionUID = -5008541658519841090L;
private String id;
private String name;
private Data() { }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Json:
json: {"id":"10861234","name":"Whatever","email":"whatever\u0040gmail.com","friends":{"data":[{"name":"Someone","id":"10861234"},{"name" ...43"}],"paging":{"next":"https:\/\/graph.facebook.com\/10861234\/friends..."}}}
The fields ID, Name and Email I can retrieve succesfully... but the friendsList is null... =(
Maybe it is the way I am trying to get it from the nested class, any suggestions on that?
There is no friendsList in your JSON (or, there's no friends in your Java class - whichever way you'd like to look at it). Gson silently ignores anything in the JSON that is not present in your classes.
You have a field friends whose value is an object. That object has a field data which is an array of objects and a field paging which is another object.
You need to write Java classes that match that structure. You're ... close.
In your FBUser class change:
private Friends friendsList = new Friends();
to:
private Friends friends = new Friends();
or:
#SerializedName("friends")
private Friends friendsList = new Friends();
Then in your Friends class you need to add:
private Paging paging = new Paging();
Also note that you don't have to initialize these values unless you specifically don't want them to be non-null when using these classes elsewhere.