I have these classes
public class Application {
public String name;
public String ico;
public List<MenuStruct> menu =new ArrayList<MenuStruct>();
//Constructor
public Application() { }
}
public class MenuStruct {
public String id;
public String type;
public String parent;
public String name;
public String secId;
//Constructor
public MenuStruct() {}
}
If I try to deserialize a collection directly in this way:
ApplicationManager apm= new ApplicationManager();
s="[ {\"name\":\"reg_salida\" , \"ico\":\"document-open-2-32x32.ico\" }]";
apm.apps=(new Gson()).fromJson(s,apm.apps.getClass() );
for (Application ap:apm.apps){
System.out.println(ap.name); //gets error here
}
I get a java.lang.ClassCastException.
But if I try to deserialize its containig class ApplicationManager it does not fail.
s="{ \"apps\": [ {\"name\":\"reg_salida\" , \"ico\":\"document-open-2-32x32.ico\" }]}";
ApplicationManager apm=(new Gson()).fromJson(s,ApplicationManager.class);
for (Application ap:apm.apps){
System.out.println(ap.name); // now no errors here! and shows reg_salida
}
Is this a bug of gson 2.2.4? or maybe I am doing something not correct?
Eduard.
You have to provide full definition of property class. Your example should looks like that:
manager.apps = gson.fromJson(json, new TypeToken<List<Application>>() {}.getType());
Related
I have a Mongo - Java MVC Spring 4 connectivity. My insert operations work only once, they don't do a second insert in the collection. What could be the problem?
Here's my code.
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="subject")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;
private String name;
private String email;
private String address;
private String telephone;
strong text
...
public class EmployeeDAOImpl implements EmployeeDAO {
MongoTemplate mongoTemplate;
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
#Override
public void addEmployee(Employee employee) {
mongoTemplate.save(employee);;
}
#Override
public List<Employee> getAllEmployees() {
// TODO Auto-generated method stub
return mongoTemplate.findAll(Employee.class);
}
#GeneratedValue(strategy=GenerationType.SEQUENCE) annotation is for JPA and not for Mongo.
Make sure that you import the #Id from the mongo package and ID should be auto generated by Mongo.
The first insert works because int has default value of 0 and the second time it tries to insert with the same key.
if you want to have custom ids generated, here is a great tutorial for that: https://www.baeldung.com/spring-boot-mongodb-auto-generated-field
I am getting null while reading the values from .properties file when i am executing the test case. here while debugging the test case i am able to see the values which are loaded from properties file when the curser is there in the test class but when the curser enters into the actual class in that class i am getting the same values as null. And my code is as follows
Thanks in advance
#RestController
#PropertySource("classpath:/com/example/prop.properties")
public class ReadProp {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#RequestMapping(value="/")
public void getDetails(){
System.out.println(name);
System.out.println(rollNo);
}
}
and the test case is as follows
#RunWith(SpringRunner.class)
#SpringBootTest
#PropertySource("classpath:/com/example/prop.properties")
public class ReadPropTest {
private ReadProp readProp = new ReadProp();
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
#Test
public void readValues() {
System.out.println(name);
System.out.println(rollNo);
readProp.getDetails();
}
}
Instead of creating a new object using new ReadProp(). You should Autowire it.
#Autowired
ReadProp readProp;
in your test class. If you create an object using new, you don't get the bean which spring created with all the value assigned using #Value.
Try something like this :
#PropertySource("classpath:prop.properties")// your error
public class ReadPropTest {
#Value("${name}")
private String name;
#Value("${rollNo}")
private String rollNo;
}
I am working with Realm ORM for my application. My Application has three Model classes that extends RealmObject. In one of the class I have defined a List of object which is creating problem.
my first class;
public class Party extends RealmObject implements Parcelable{
public String name;
public String name_en;
public String name_ne;
public String address;
public String phoneNumber;
//get and setters
//parceable
}
My second class;
public class CreatePurchaseOrderRow extends RealmObject implements Parcelable {
public String name;
public float amount;
public String specification;
public String remarks;
public Party party;
// getter setter
//parceable
}
And finally My third class implements List of objects of Second class. that is,
public class CreatePurchasOrder extends RealmObject implements Parcelable {
public int num;
public Date date;
public List<CreatePurchaseOrderRow> createPurchaseOrderRows;
//getter setter
//parceable
}
the List feeds is creating problem.
i have the screenshot for error message here
Realm is not schemaless database. I tried finding the solutions but i cannot. Can anyone help me with this?
Thanks in Advance
RealmObjects can not have fields of type List<>(java.util.List), you have to use RealmList<> instead:
public class CreatePurchasOrder extends RealmObject implements Parcelable {
public int num;
public Date date;
public RealmList<CreatePurchaseOrderRow> createPurchaseOrderRows;
//getter setter
//parceable
}
See also: https://realm.io/docs/java/latest/#many-to-many
I define an object like
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
public String getTotalMileage () {
return totalMileage;
}
public void setTotalMileage (String totalMileage) {
this.totalMileage = totalMileage;
}
public String getMileageTime () {
return mileageTime;
}
public void setMileageTime (String mileageTime) {
this.mileageTime = mileageTime;
}
}
}
and my controller is like:
#RequestMapping(value="saveDriveLog",method = RequestMethod.GET)
public #ResponseBody ResultBean saveDriveLog(DrivelogBean drivelogBean){
driveLogService.addDriveLog (drivelogBean);
ResultBean resultBean = new ResultBean();
resultBean.setRet (1);
resultBean.setDescripion (UsConstants.DRIVELOG_SAVE);
return resultBean;
}
I want request parameters convert to drivelogBean
and my url is like that:
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?backInfoIdentify=2&totalMileageIntd["driverNum%22]=1&totalMileageIntd["driveCode"]=2
but the page prompt
HTTP ERROR: 404 Problem accessing //manage/drivelog/saveDriveLog/error. Reason:Not Found
and i change the url like :
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?commendWord=2&totalMileageIntd.driverNum=1&totalMileageIntd.driveCode=2
but the drivelogBean parameter, the property driverNum of totalMileageIntd and the property driveCode of totalMileageIntd is null.
So how can I set the correct url pass parameter to the drivelogBean?
I don't know if binding inner static class works in spring.
Your parametter must match a setter
commendWord=2 => you must have setCommendWord on the class DrivelogBean
totalMileageIntd.driverNum=1 => you must have a setDriverNum() on and a getTotalMileageIntd
The class should look like this (I skipped getter and setter to save space but they must exists)
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
private TotalMileageIntd totalMileageIntd ;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
}
}
In this case all the parametter you can use are :
backInfoIdentify=XXX
driVehNum=XXX
totalMileageIntd.totalMileage=XXX
totalMileageIntd.mileageTime=XXX
nothing else
Adobe Flex Builder WSDL classes autogenerator generates wierd files.
For example:
http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl
After importing it generates these files:
ArrayOfForecast.as
ArrayOfWeatherDescription.as
ArrayOfWeatherDescription0.as
BaseWeather.as
BaseWeatherSchema.as
Forecast.as
ForecastReturn.as
ForecastReturn0.as
GetCityForecastByZIPResultEvent.as
GetCityForecastByZIP_request.as
GetCityWeatherByZIPResultEvent.as
GetCityWeatherByZIP_request.as
GetWeatherInformationResultEvent.as
GetWeatherInformation_request.as
IWeather.as
POP.as
Temp.as
Weather.as
WeatherDescription.as
WeatherReturn.as
WeatherReturn0.as
What are these ZERO at the end files for?
That was an example for service with 3 operations. My real wsdl has much more methods and types.
UPDATED
At the same time Java generates much cleaner set of classes:
Forecast.java
ForecastReturn.java
POP.java
Temp.java
WeatherDescription.java
Weather.java
WeatherLocator.java
WeatherReturn.java
WeatherSoap12Stub.java
WeatherSoap.java
WeatherSoapProxy.java
WeatherSoapStub.java
It's not noticeable for such small service, but for bigger service with more operations and types it generates hundreds of classes. I have doubt that Adobe Flex team does wsdl classes autogeneration in proper way.
UPDATE-2
WeatherReturn.as:
public class WeatherReturn
{
/**
* Constructor, initializes the type class
*/
public function WeatherReturn() {}
public var Success:Boolean;
public var ResponseText:String;
public var State:String;
public var City:String;
public var WeatherStationCity:String;
public var WeatherID:Number;
public var Description:String;
public var Temperature:String;
public var RelativeHumidity:String;
public var Wind:String;
public var Pressure:String;
public var Visibility:String;
public var WindChill:String;
public var Remarks:String;
}
WeatherReturn0.as:
public class WeatherReturn0
{
/**
* Constructor, initializes the type class
*/
public function WeatherReturn0() {}
public var WeatherReturn:com.cdyne.WeatherReturn;
}
WeatherReturn.java:
public class WeatherReturn implements java.io.Serializable {
private boolean success;
private java.lang.String responseText;
private java.lang.String state;
private java.lang.String city;
private java.lang.String weatherStationCity;
private short weatherID;
private java.lang.String description;
private java.lang.String temperature;
private java.lang.String relativeHumidity;
private java.lang.String wind;
private java.lang.String pressure;
private java.lang.String visibility;
private java.lang.String windChill;
private java.lang.String remarks;
// Skipped constructors and getter/setter
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj)
private boolean __hashCodeCalc = false;
public synchronized int hashCode()
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(WeatherReturn.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://ws.cdyne.com/WeatherWS/", "WeatherReturn"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("success");
elemField.setXmlName(new javax.xml.namespace.QName("http://ws.cdyne.com/WeatherWS/", "Success"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("responseText");
// More typedesc here ...
}
public static org.apache.axis.description.TypeDesc getTypeDesc() {
public static org.apache.axis.encoding.Serializer getSerializer(
public static org.apache.axis.encoding.Deserializer getDeserializer(
}
I left only methods signatures for Java example and skipped getters/setters.