I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.
My goal is to modify my setters to throw tractorException if invalid values are passed in then modify my main method to try and catch the exceptions. The problem is I do not know how to modify my setters to make a exception error. Please Help.
import java.util.*;
public class tractorException
{
protected String name;
protected int VehicleID;
public String setName(String name)
{
return this.name = name;
}
String getName()
{
return this.name;
}
public int setVehicleID(int VehicleID)
{
if (VehicleID <= 0 || VehicleID > 100000)
{
return -1;
}
else
{
this.VehicleID = VehicleID;
return VehicleID;
}
}
public int getVehicleID()
{
return this.VehicleID;
}
tractorException()
{
setVehicleID(0);
setName("");
}
#Override
public String toString()
{
return "Tractor Name= " + name + "VIN= " + VehicleID;
}
public static void main (String[] args)
{
}
}
Try doing:
public class TractorException extends Exception
{
//implement whatever methods are necessary
}
In a class that represents a Tractor.
public int setVehicleID(int VehicleID) throws TractorException
{
if (VechicleID <= 0) {
throw new TractorException("Invalid VIN: " + VehicleID);
}
else {
this.VehicleID = VehicleID;
return this.VehicleID;
}
}
In your main method, catch TractorException
I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.
I am still new to Android, I'm primarily an iOS developer.
I don't know why I can't test to see whether or not the ListArray is empty or not. I need to test and use the size of it anyways.
This is declared within the class:
Projects projects = new Projects();
The following code does not like projects.videos.size() being compared nil or 0.
try
{
if (projects != null)
{
int numberOfVideos = projects.videos.size();
if(numberOfVideos==0)
{
// myStringArray = new String[projects.videos.size()];
//
//
//
// for (int i = 0;i < projects.videos.size();i++)
// {
// myStringArray[i] = projects.videos.get(i);
// }
}
else
{
// myStringArray = new String[1];
// myStringArray[0] = "No projects";
}
}
else
{
System.out.println("Sucess");
}
}
catch (Exception e)
{
System.out.println(e);
System.out.println("somethingbad has happened");
System.out.println(projects.videos.size());
}
This is what the projects class looks like:
package com.example.musicvideomaker;
import java.util.ArrayList;
import java.util.UUID;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Projects implements Serializable{
public String projectName;
public String musicStuff;
public String songTitle;
public String guid;
public boolean isBuiltVideo;
public boolean isListOfBuiltVideos;
public int selectedIndex;
public ArrayList<String> videos;
public ArrayList<String> builtVideos;
public ArrayList<Number> tPoints;
public void setProjectName(String projectName)
{
this.projectName = projectName;
}
public void setMusicStuff(String musicStuff)
{
this.musicStuff = musicStuff;
}
public void setSongTitle(String songTitle)
{
this.songTitle = songTitle;
}
public void setGuid()
{
UUID uuid = UUID.randomUUID();
this.guid = uuid.toString();
}
public void isBuiltVideo(boolean isBuiltVideo)
{
this.isBuiltVideo = isBuiltVideo;
}
public void isListOfBuiltVideos(boolean isListOfBuiltVideos)
{
this.isListOfBuiltVideos = isListOfBuiltVideos;
}
public void setSelectedIndex(int selectedIndex)
{
this.selectedIndex = selectedIndex;
}
public void addRecordedVideo(String recordedVideo)
{
this.videos.add(recordedVideo);
}
public void addBuiltVideo(String builtVideo)
{
this.builtVideos.add(builtVideo);
}
public void addTPoint(Number tPoint)
{
this.tPoints.add(tPoint);
}
}
I removed int numberOfVideos = projects.videos.size();
Instead of using if(numberOfVideos==0) I used projects.videos == null
I think it was because my projects are null so it crashes when trying to pull the size of the arrayList.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
java.net.MalformedURLException: no protocol: "localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:464)
at java.net.URL.<init>(URL.java:413)
Malformed URL exception when reading data from url containing localhost.
Actually my program is as below
package bll.sap;
import java.net.MalformedURLException;
import utility.PropertyUtility;
public class GetActiveData
{
public static void main(String[] args) {
String sapURL = "";
try {
sapURL = PropertyUtility.getSapURL();
//Get Summary Data
SapDataSync sapDataSync = new SapDataSync();
//sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=false");
sapDataSync.readTransactionJsonFromUrl(sapURL+"?isx=E13F42EC5E38");
}
catch(MalformedURLException me)
{
me.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AND
package bll.sap;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import utility.Utility;
import com.google.code.morphia.Datastore;
import dal.GetMorphiaDB;
public class SapDataSync
{
private void saveSapTransaction(List<TransactionUnit> sapTransaction){
GetMorphiaDB morphia;
try {
morphia = GetMorphiaDB.getInstance();
Datastore ds = morphia.getDs();
ds.save(sapTransaction);
}catch (Exception e) {
e.printStackTrace();
}
}
private void createSapTransaction(String transactionJson){
JSONObject jsonObj = JSONObject.fromObject(transactionJson);
JSONArray transactionUnits = jsonObj.getJSONArray("TRANSACTION");
List<ActiveUnit> transactionList = new ArrayList<ActiveUnit>();
for(int i = 0; i < transactionUnits.size() ; i++){
JSONObject jsn = transactionUnits.getJSONObject(i);
JSONObject jsnFeed = transactionUnits.getJSONObject(i);
ActiveUnit transactionUnit = new ActiveUnit(
jsn.getString("listEditions"),
jsn.getString("listPackage"),
//Double.parseDouble(jsn.getString("YIELD")),
//Double.parseDouble(jsn.getString("QUANTITY")),
//Double.parseDouble(jsn.getString("VALUE")),
jsn.getString("referenceID")
//jsn.getString("PRICEGROUP"),
//jsn.getString("PAGE"),
//Utility.getCalendarTime(jsn.getString("PUBDATE"), "dd-MM-yyyy"),
//jsn.getString("CLIENTNAME"),
//jsn.getString("CLIENTCODE"),
// new Date().getTime(),
//jsn.getString("BOOKINGUNITNAME"),
//jsn.getString("BCCNAME"),
//jsn.getString("PAGENAME"),
// jsn.getString("PRICEGROUPNAME"),
// jsn.getString("ORDER"),
// jsn.getString("PAGE_LH_RH")
);
transactionList.add(transactionUnit);
System.out.println(transactionList);
}
System.out.println(transactionList.size());
if (transactionList.size() > 0) {
//saveSapTransaction(transactionList);
}
}
public void readTransactionJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
createSapTransaction(sb.toString());
} finally {
is.close();
}
}
}
AND
package bll.sap;
import java.io.Serializable;
import java.util.Date;
import org.bson.types.ObjectId;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
#Entity("SapTransaction")
public class ActiveUnit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private ObjectId id;
private Long tilCreationDate;
private String clientName;
private String clientCode;
private String listEditions;
private Long date;
private String listPackage;
private String bookingUnitName;
private String referenceID;
private String bccName;
private String page;
private String pageName;
private String priceGroup;
private String pgName;
private Double yield;
private Double qty;
private Double value;
private String order;
private String pageType;
public ActiveUnit() {
}
public ActiveUnit(String listEdtions, String listPackage, /*Double yield,
Double qty, Double value,*/ String referenceID /*, String priceGroup,
String page, Long date,String clientName,
String clientCode,Long tilCreationDate,String bookingUnitName,String bccName,String pageName,String pgName,String order,String pageType*/) {
this.listEditions = listEdtions;
this.listPackage = listPackage;
//this.yield = yield;
//this.qty = qty;
//this.value = value;
this.referenceID = referenceID;
//this.priceGroup = priceGroup;
//this.page = page;
//this.date = date;
//this.clientName = clientName;
//this.clientCode = clientCode;
//this.tilCreationDate = tilCreationDate;
//this.setBookingUnitName(bookingUnitName);
//this.bccName = bccName;
//this.pageName = pageName;
//this.pgName = pgName;
//this.order = order;
//this.pageType = pageType;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientCode() {
return clientCode;
}
public void setClientCode(String clientCode) {
this.clientCode = clientCode;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getId() {
return id;
}
public void setTilCreationDate(Long tilCreationDate) {
this.tilCreationDate = tilCreationDate;
}
public Long getTilCreationDate() {
return tilCreationDate;
}
public String getreferenceID() {
return referenceID;
}
public void setreferenceID(String referenceID) {
this.referenceID = referenceID;
}
public String getPriceGroup() {
return priceGroup;
}
public void setPriceGroup(String priceGroup) {
this.priceGroup = priceGroup;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getListEditions() {
return listEditions;
}
public void setVertical(String listEditions) {
this.listEditions = listEditions;
}
public String getListPackage() {
return listPackage;
}
public void setListPackage(String listPackage) {
this.listPackage = listPackage;
}
public Double getYield() {
return yield;
}
public void setYield(Double yield) {
this.yield = yield;
}
public Double getQty() {
return qty;
}
public void setQty(Double qty) {
this.qty = qty;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public void setBookingUnitName(String bookingUnitName) {
this.bookingUnitName = bookingUnitName;
}
public String getBookingUnitName() {
return bookingUnitName;
}
public String getBccName() {
return bccName;
}
public void setBccName(String bccName) {
this.bccName = bccName;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public String getPgName() {
return pgName;
}
public void setPgName(String pgName) {
this.pgName = pgName;
}
#Override
public String toString() {
String unit = "{ " +
//"ClientCode: " + this.clientCode+
//",TILCreation Date: " + new Date(this.tilCreationDate)+
//",ClientName: "+ this.clientName+
"listEditions: " + this.listEditions+
",listPackage: "+ this.listPackage+
//",BookingUnitName: "+ this.bookingUnitName+
//",Yield: " + this.yield+
//",QTY: " + this.qty+
//",Value: " + this.value+
",referenceID: " + this.referenceID+
//",Price Group: " + this.priceGroup+
//",BCCName: " + this.bccName+
//",PageName: " + this.pageName+
//",PriceGroupName: " + this.pgName+
//",Page: " + this.page+
//",PageType: " + this.pageType+
//",Order: " + this.order+
//",PublishDate: " + new Date(this.date) +
" }";
return unit;
}
public void setOrder(String order) {
this.order = order;
}
public String getOrder() {
return order;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getPageType() {
return pageType;
}
}
First, make sure you have the protocol set for your request.
Second, make sure that the String containing the URL is URL-encoded. I.e. the URL doesn't have any spaces and other special characters - these should be encoded (space is %20 etc).
Given that the two above are met, your program should not throw an exception from the java.net.URL class.
Looking at the exception above, you'll just have to set the protocol (http://), but do make sure that you encode your URL address strings properly or else you'll get exceptions from other parts of your program.
Also, adding http:// to the following string will also result in a MalformedURLException:
"localhost/uatpw/ActiveTransaction"?isx=E13F42EC5E38 as your URL would contain special characters (" in this case) which would need to be encoded.
To provide a valid URL you should make sure that the quotes are stripped from your URL's server and path segments areas:
localhost/uatpw/ActiveTransaction?isx=E13F42EC5E38. Prepeding http:// to this will result in a valid URL.
You are missing the protocol (e.g. http://) in front of localhost.
The welformed URL could be http://localhost/uatpw/ActiveTransaction
This is not a question. What are you trying to do?
But otherwise, "localhost/uatpw/ActiveTransaction" is not a valid URL. An url must start with a protocol (http, https, ftp, etc.).
You should try with:
http://localhost/uatpw/ActiveTransaction