I have some JSON objects and I need to changed them as JAVA classes and assign the given value.
{
"Summary":{
"AccountSummary":{
"Account_number": "324d",
"Account_name": "John"
},
"Transaction":[
{
"Date": "2021-08-21",
"Amount": "20,000"
},
{
"Date": "2021-08-23",
"Amount": "5,000"
}
]
}
}
These are the current coding I did,
//The account summary class with assigned value
public class AccountSummary{
#JsonProperty("Account_number")
public String account_number = "324d";
#JsonProperty("Account_name")
public String account_name = "John";
}
//Transaction class. I want to know how I can assign values
public class Transaction{
#JsonProperty("Date")
public String date;
#JsonProperty("Amount")
public String amount;
}
// Summary class
public class Summary{
#JsonProperty("AccountSummary")
public AccountSummary accountSummary;
#JsonProperty("Transaction")
public List<Transaction> transaction;
}
As I have assigned values for AccountSummary, I need to assign values for Transaction class also. But As if its a list I don't know how to assign. Please help.
You can do something like this,
First, create a maven project which has the below dependencies,
1. jackson-core
2. jackson-databind
3. jackson-annotations
make sure to have all three dependencies in the same version.
Then create separate model classes for your POJO objects
public class AccountSummary{
#JsonProperty("Account_number")
public String account_number;
#JsonProperty("Account_name")
public String account_name;
}
public class Transaction{
#JsonProperty("Date")
public String date;
#JsonProperty("Amount")
public String amount;
}
public class Summary{
#JsonProperty("AccountSummary")
public AccountSummary accountSummary;
#JsonProperty("Transaction")
public List<Transaction> transaction;
}
public class Root{
#JsonProperty("Summary")
public Summary summary;
}
Then create a Main.java class and implement the below code.
public class Main {
public static void main(String[] args) {
try {
ObjectMapper om = new ObjectMapper();
Root root = om.readValue(new File("your.value.json"),Root.class);
System.out.println(root);
} catch (Exception e) {
e.printStackTrace();
}
}
}
now when you execute you can see all the values in the json file are assigned correctly to your models.
So like this, you can map your json values to your objects.
You can try following for setting the value manually
Summary.java
public class Summary {
public AccountSummary accountSummary;
public List<Transaction> transaction;
public AccountSummary getAccountSummary() {
return accountSummary;
}
public void setAccountSummary(AccountSummary accountSummary) {
this.accountSummary = accountSummary;
}
public List<Transaction> getTransaction() {
return transaction;
}
public void setTransaction(List<Transaction> transaction) {
this.transaction = transaction;
}
}
Transaction.java
public class Transaction {
public String date;
public String amount;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
AccountSummary .java
public class AccountSummary {
public String account_number;
public String account_name;
public String getAccount_number() {
return account_number;
}
public void setAccount_number(String account_number) {
this.account_number = account_number;
}
public String getAccount_name() {
return account_name;
}
public void setAccount_name(String account_name) {
this.account_name = account_name;
}
}
final Code:-
AccountSummary a = new AccountSummary();
a.setAccount_name("xyz");
a.setAccount_number("xyz");
List<Transaction> transactionList = new ArrayList<Transaction>();
Transaction t = new Transaction();
t.setAmount("xyz");
t.setDate("xyx");
transactionList.add(t); // set the multiple object
// here is the final result
Summary s = new Summary();
s.setAccountSummary(a);
s.setTransaction(transactionList);
Related
I'm trying to parse a JSON file which I get via API to pojo. After searching on internet I see boon is working with rest but I can't figure out how.
According to this article it should work but....
In my code HTTP.getJSON() method require a map as parameter which I can't figure out what exactly this map is.
Any genius one can give a working example of boon?
public class ViewTimeline{
public void view() {
ObjectMapper mapper = JsonFactory.create();
List<String> read = IO.readLines("https://corona-api.com/timeline");
Map<String, ?> headers = null ;
List<Timeline> timelineList = mapper.readValue(HTTP.getJSON("https://corona-api.com/timeline", headers), List.class, Timeline.class);
}
}
TimeLine.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"updated_at",
"date",
"deaths",
"confirmed",
"recovered",
"active",
"new_confirmed",
"new_recovered",
"new_deaths",
"is_in_progress"
})
public class Timeline {
#JsonProperty("updated_at")
private String updatedAt;
#JsonProperty("date")
private String date;
#JsonProperty("deaths")
private Integer deaths;
#JsonProperty("confirmed")
private Integer confirmed;
#JsonProperty("recovered")
private Integer recovered;
#JsonProperty("active")
private Integer active;
#JsonProperty("new_confirmed")
private Integer newConfirmed;
#JsonProperty("new_recovered")
private Integer newRecovered;
#JsonProperty("new_deaths")
private Integer newDeaths;
#JsonProperty("is_in_progress")
private Boolean isInProgress;
#JsonProperty("updated_at")
public String getUpdatedAt() {
return updatedAt;
}
#JsonProperty("updated_at")
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
#JsonProperty("date")
public String getDate() {
return date;
}
#JsonProperty("date")
public void setDate(String date) {
this.date = date;
}
#JsonProperty("deaths")
public Integer getDeaths() {
return deaths;
}
#JsonProperty("deaths")
public void setDeaths(Integer deaths) {
this.deaths = deaths;
}
#JsonProperty("confirmed")
public Integer getConfirmed() {
return confirmed;
}
#JsonProperty("confirmed")
public void setConfirmed(Integer confirmed) {
this.confirmed = confirmed;
}
#JsonProperty("recovered")
public Integer getRecovered() {
return recovered;
}
#JsonProperty("recovered")
public void setRecovered(Integer recovered) {
this.recovered = recovered;
}
#JsonProperty("active")
public Integer getActive() {
return active;
}
#JsonProperty("active")
public void setActive(Integer active) {
this.active = active;
}
#JsonProperty("new_confirmed")
public Integer getNewConfirmed() {
return newConfirmed;
}
#JsonProperty("new_confirmed")
public void setNewConfirmed(Integer newConfirmed) {
this.newConfirmed = newConfirmed;
}
#JsonProperty("new_recovered")
public Integer getNewRecovered() {
return newRecovered;
}
#JsonProperty("new_recovered")
public void setNewRecovered(Integer newRecovered) {
this.newRecovered = newRecovered;
}
#JsonProperty("new_deaths")
public Integer getNewDeaths() {
return newDeaths;
}
#JsonProperty("new_deaths")
public void setNewDeaths(Integer newDeaths) {
this.newDeaths = newDeaths;
}
#JsonProperty("is_in_progress")
public Boolean getIsInProgress() {
return isInProgress;
}
#JsonProperty("is_in_progress")
public void setIsInProgress(Boolean isInProgress) {
this.isInProgress = isInProgress;
}
}
To parse an json to an object, I used Jackson. I also saw you used Jackson at mapping in Timeline.
Jackson Core: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.11.0
Jackson Databind: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.11.0
Jackson Annotation: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations/2.11.0
This is the way I handled it:
public static void main(String[] args) throws JsonProcessingException {
//my method to read content from website.
//using apache http
String jsonApi = getApi();
ObjectMapper objectMapper = new ObjectMapper();
//todo JsonProcessingException
JsonNode data = objectMapper.readTree(jsonApi);
//get data field from data, which is an array
//todo This can throws error if data field is missing
JsonNode dataArray = data.get("data");
List<Timeline> timelineList = new ArrayList<>();
if(dataArray.isArray()){
for(JsonNode line : dataArray){
//todo this can throws errors. need to handle it.
Timeline timeline = objectMapper.readValue(line.toString(), Timeline.class);
timelineList.add(timeline);
}
}else{
System.out.println("JsonApi is not array: '" + jsonApi + "'");
}
System.out.println("Size: " + timelineList.size());
for(Timeline timeline : timelineList){
System.out.println(timeline.getConfirmed());
}
}
At this code you should handle the exceptions. I marked them by comments.
I'm trying to read the values from a JSON URL, however I don't know how I can proceed with reading the values from a List inside of an Array? Below you will find my POJO, Main, and JSON code. Thank you so much for your help
POJO:
package org.jcexchange.FBApp;
import java.util.List;
import org.jcexchange.FBApp.Details;
public class Users {
private List<Details> Values;
public List<Details> getValues() {
return this.Values;
}
public void setValues(List<Details> Values) {
this.Values = Values;
}
}
public class Details {
private String user_name;
private String user_password;
private int age;
private String user_email;
public String getUserName() {
return this.user_name;
}
public void setUserName(String user_name) {
this.user_name = user_name;
}
public String getUserPassword() {
return this.user_password;
}
public void setUserPassword(String user_password) {
this.user_password = user_password;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserEmail() {
return this.user_email;
}
public void setUserEmail(String user_email) {
this.user_email = user_email;
}
}
Main:
public class Main {
public static void main(String[] args) {
try {
URL jsonURL = new URL("https://jchtest.herokuapp.com/index.php?
PW=2");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
Users[] a1 = mapper.readValue(jsonURL, Users[].class);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
I'm able to pull the JSON from a webservice, however I'm stuck trying to figure out how I could retrieve for instance the user_name from the first "Values" index of the JSON array
JSON:
[
{
"Values": {
"user_name": "jhart",
"user_password": "gooddeval1",
"age": 28,
"user_email": "heheh"
}
},
{
"Values": {
"user_name": "bdole",
"user_password": "Passwordd",
"age": 82,
"user_email": "hahah"
}
}
]
Well , it is a little confusing here may be because i dont have the full context. From the de-serializer you are telling me that i expect an Array of Users and then within each User i have a List of "Values" , but the JSON tells me that Values is a singular property for Users. Anyways , here is a sample that works on the assumption i have made. This can be fiddled around to change the collection and singular properties
import org.codehaus.jackson.annotate.JsonProperty;
public class Users {
#JsonProperty("Values")
private Details Values;
public Details getValues() {
return this.Values;
}
public void setValues(Details Values) {
this.Values = Values;
}
}
import org.codehaus.jackson.annotate.JsonProperty;
public class Details {
#JsonProperty("user_name")
private String user_name;
#JsonProperty("user_password")
private String user_password;
#JsonProperty("age")
private int age;
#JsonProperty("user_email")
private String user_email;
public String getUserName() {
return this.user_name;
}
public void setUserName(String user_name) {
this.user_name = user_name;
}
public String getUserPassword() {
return this.user_password;
}
public void setUserPassword(String user_password) {
this.user_password = user_password;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserEmail() {
return this.user_email;
}
public void setUserEmail(String user_email) {
this.user_email = user_email;
}
}
import java.net.URL;
import org.codehaus.jackson.map.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
URL jsonURL = new URL("https://jchtest.herokuapp.com/index.php?PW=2");
ObjectMapper mapper = new ObjectMapper();
Users[] a1 = mapper.readValue(jsonURL, Users[].class);
System.out.println(a1[0].getValues().getUserName());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
This prints "jhart" for me.
Please note : One thing you can try is based on the array/singular property you can populate the Object and write it as JSON. That way you can find what is different in what Jackson Deserializer expects vs What we are actually supplying.
I'm being given a Json file with the form:
{
"descriptions": {
"desc1": "someString",
"desc2": {"name":"someName", "val": 7.0}
}
}
I have the POJO:
public class CustomClass {
Map<String, Object> descriptions;
public static class NameVal{
String name;
double val;
public NameVal(String name, double val){...}
}
}
I can recreate the json file with the code:
CustomClass a = new CustomClass();
a.descriptions = new HashMap<String, Object>();
a.descriptions.put("desc1", "someString");
a.descriptions.put("desc2", new CustomClass.NameVal("someName", 7.0));
new ObjectMapper().writeValue(new File("testfile"), a);
But, when I read the object back in using:
CustomClass fromFile = new ObjectMapper().readValue(new File("testfile"), CustomClass.class);
then fromFile.descriptions.get("desc2") is of type LinkedHashMap instead of type CustomClass.NameVal.
How can I get Jackson to properly parse the type of the CustomClass.NameVal descriptors (other than making some class that wraps the parsing and explicitly converts the LinkedHashMap after Jackson reads the file)?
Try this. Create a class Description with name and value attributes:
public class Description {
private String name;
private double val;
}
Now in your CustomClass do this:
public class CustomClass {
List<Description> descriptions;
}
And that's it. Remember to create getters and setters because Jackson needs it.
You could try something like this:
public class DescriptionWrapper {
private Description descriptions;
public Description getDescriptions() {
return descriptions;
}
public void setDescriptions(Description descriptions) {
this.descriptions = descriptions;
}
}
public class Description {
private String desc1;
private NameValue desc2;
public String getDesc1() {
return desc1;
}
public void setDesc1(String desc1) {
this.desc1 = desc1;
}
public NameValue getDesc2() {
return desc2;
}
public void setDesc2(NameValue desc2) {
this.desc2 = desc2;
}
}
public class NameValue {
private String name;
private double val;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getVal() {
return val;
}
public void setVal(double val) {
this.val = val;
}
}
I have a java-programme:
public class Faculty
{
String facultyName;
Double gemavailable;
}
public class Session
{
String coursename;
float noofhours;
ArrayList<Faculty> faculty=new ArrayList<>();
}
public class TrainingInstitute
{
ArrayList<Faculty> faculty=new ArrayList<>();
ArrayList<Session> session=new ArrayList<>();
public void takeASession(String coursename,float hours,ArrayList<Faculty> faculty)
{
Session s=new Session(coursename, hours, faculty);
session.add(s);
}
And I have the main class which looks like:
public class TrainingController
{
public static void main(String[] args)
{
TrainingInstitute t=new TrainingInstitute();
t.takeASession("java", 5,f1);
}
My main motive is to create a session object by setting the course name,faculty who had taken the course and duration of the course.And the session object is added to the sessionTaken list of Training Institute.
How would i do that ?
There are two ways to do this
Either you could have an overload constructor on Session class and push in one faculty to start with and then incrementally add faculty using the addFaculty method.
public class Session {
private String coursename;
private float noofhours;
private ArrayList<Faculty> faculty=new ArrayList<Faculty>();
public Session(String courseName, float noOfHours, Faculty faculty){
this.coursename=courseName;
this.noofhours=noOfHours;
this.faculty.add(faculty);
}
public Session(String courseName, float noOfHours, ArrayList<Faculty> faculty){
this.coursename=courseName;
this.noofhours=noOfHours;
this.faculty=faculty;
}
public void addFaculty(Faculty faculty){
this.faculty.add(faculty);
}
}
Else you could do a
t.takeASession("java", 5,new ArrayList(){{add(f1);}});
To be able to instantiate your Session object as follows:
Session s = new Session(coursename, hours, faculty);
you need to define a constructor like that in you Session class
public class Session {
private String courseName;
private float noOfHours;
private List<Faculty> faculties;
public Session(String courseName, float noOfHrs, List<Faculty> faculties) {
this.courseName = courseName;
this.noOfHours = noOfHrs;
this.faculties = faculties;
}
You should use List (the interface) instead of ArrayList (an implementation) as the type of your list. Also, you should ecapsulte the fields in your classes.
Here's what I'd do
public class TrainingController {
public static void main(String[] args) {
Faculty faculty1 = new Faculty("NY", 200.0);
List<Faculty> faculties = new ArrayList<Faculty>();
faculties.add(faculty1);
TrainingInstitute training=new TrainingInstitute();
training.takeASession( new Session("java", 5, faculties) );
training.takeASession( new Session("php", 4, faculties) );
System.out.println(training);
}
}
class Faculty {
String facultyName;
double gemavailable;
public Faculty(String facultyName, Double gemavailable) {
this.facultyName = facultyName;
this.gemavailable = gemavailable;
}
public String toString(){
return facultyName+" "+gemavailable;
}
}
class Session {
String coursename;
float noofhours;
List<Faculty> faculties;
public Session(String coursename, float noofhours,
List<Faculty> faculties) {
this.coursename = coursename;
this.noofhours = noofhours;
this.faculties = faculties;
}
public List<Faculty> getFaculties() {
return faculties;
}
public String toString(){
return coursename+" "+noofhours+" "+faculties;
}
}
class TrainingInstitute {
Set<Faculty> faculties = new HashSet<Faculty>();
List<Session> sessions = new ArrayList<Session>();
public void takeASession(Session session) {
sessions.add(session);
faculties.addAll(session.getFaculties());
for (Faculty faculty: faculties){
faculty.gemavailable -= session.noofhours;
}
}
public String toString(){
return "faculties: " + faculties + "\nsessions:" + sessions;
}
}
Sorry for posting late,but this is how i got my prorram run:
public class TrainingInstitute
{
private ArrayList<Faculty> faculty1=new ArrayList<Faculty>();
private ArrayList<Session> session1=new ArrayList<Session>();
public void takeASession(String facname,String cname,float noOfhours)
{
Session s=new Session(cname, noOfhours,new Faculty(facname));
session1.add(s);
System.out.println("The session for"+""+facname+"is added and the size is:"+session1.size());
}
I need to design a report, that displays the data from a collection(Say List). This list contains multiple POJOs.
The POJOs are populated by the data access layer of the application. How do I design a report template for this requirement in iReports?
Use JRBeanCollectionDataSource for your report.
Ok! Found the answer. The steps are as below.
Compile the bean classes and create a JAR file. This needs to have the complete package
Add this jar to the LIB folder in ireports
Create a factory/wrapper class that has a createBeanCollection method that populates a collection
Use this class's top level package as the class path in ireports
Use this class as the JavaBean datasource with the method.
Once all this is done, create a report with the new datasource and in report query, give the FQN on the Java bean and add the desired field.
BankDetailsList list = new BankDetailsList();
ArrayList<BankDetails> lst = list.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(lst);
Here BankDetails is a POJO
public class BankDetails {
public String bank_name;
public Account account;
public String custodian_account;
public String custodian_name;
public String agreement_type;
public double exposure;
public double collateral;
public double independant_amount;
public double net_exposure;
BankDetails(String b_name, Account acc, String cust_account,
String cust_name, String agr_type, double expo, double collat,
double independant_amt, double net_exp) {
this.bank_name = b_name;
this.account = acc;
this.custodian_account = cust_account;
this.custodian_name = cust_name;
this.agreement_type = agr_type;
this.exposure = expo;
this.collateral = collat;
this.independant_amount = independant_amt;
this.net_exposure = net_exp;
}
public String getBank_name() {
return bank_name;
}
public void setBank_name(String bank_name) {
this.bank_name = bank_name;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getCustodian_account() {
return custodian_account;
}
public void setCustodian_account(String custodian_account) {
this.custodian_account = custodian_account;
}
public String getCustodian_name() {
return custodian_name;
}
public void setCustodian_name(String custodian_name) {
this.custodian_name = custodian_name;
}
public String getAgreement_type() {
return agreement_type;
}
public void setAgreement_type(String agreement_type) {
this.agreement_type = agreement_type;
}
public double getExposure() {
return exposure;
}
public void setExposure(double exposure) {
this.exposure = exposure;
}
public double getCollateral() {
return collateral;
}
public void setCollateral(double collateral) {
this.collateral = collateral;
}
public double getIndependant_amount() {
return independant_amount;
}
public void setIndependant_amount(double independant_amount) {
this.independant_amount = independant_amount;
}
public double getNet_exposure() {
return net_exposure;
}
public void setNet_exposure(double net_exposure) {
this.net_exposure = net_exposure;
}
}
Account POJO:
public class Account {
public int account_id;
public String account_name;
Account(int acc_id, String acc_name){
this.account_id = acc_id;
this.account_name = acc_name;
}
public int getAccount_id() {
return account_id;
}
public void setAccount_id(int account_id) {
this.account_id = account_id;
}
public String getAccount_name() {
return account_name;
}
public void setAccount_name(String account_name) {
this.account_name = account_name;
}
}