GSON fromJSON having problems - arrays

I have a POJO class as below.
import java.util.List;
public class LocationInfoDTO{
private int _id;
private String name;
private String type;
private String fullName;
private int location_id;
private boolean isEurope;
private String countryCode;
private boolean coreCountry;
private int iataAirportCode;
private List<Geospatial> geo_location;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public int getLocation_id() {
return location_id;
}
public void setLocation_id(int location_id) {
this.location_id = location_id;
}
public boolean isEurope() {
return isEurope;
}
public void setEurope(boolean isEurope) {
this.isEurope = isEurope;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public boolean isCoreCountry() {
return coreCountry;
}
public void setCoreCountry(boolean coreCountry) {
this.coreCountry = coreCountry;
}
public int getIataAirportCode() {
return iataAirportCode;
}
public void getIataAirportCode(int iataAirportCode) {
this.iataAirportCode = iataAirportCode;
}
#Override
public String toString() {
return "LocationInfoDTO [_id=" + _id + ", name=" + name + ", type="
+ type + ", fullName=" + fullName + ", location_id="
+ location_id + ", isEurope=" + isEurope + ", countryCode="
+ countryCode + ", coreCountry=" + coreCountry
+ ", iataAirportCode=" + iataAirportCode + ", geo_location="
+ geo_location + "]";
}
public List<Geospatial> getGeo_location() {
return geo_location;
}
public void setGeo_location(List<Geospatial> geo_location) {
this.geo_location = geo_location;
}
}
All there will be inside a JSON object, just one thing the geospatial attribute has latitude and longitude and that is a different POJO class.All happens good using GSON fromJSON except the geo-location thing is null;
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":{"latitude":52.52437,"longitude":13.41053}}
This is a sample JSON.
Triggering in this way
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(json);
for(int i=0;i<array.length();i++){
System.out.println("Array:"+gson.fromJson(array.getJSONObject(i).toString(), LocationInfoDTO.class));
EDIT--------------------------------
Changed the geo-location to geo-position
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT

The error says exaclty what's wrong. You have a json object there for geo-location and it expects a list. Even if it's a one element list. Change
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":{"latitude":52.52437,"longitude":13.41053}}
to
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":[{"latitude":52.52437,"longitude":13.41053}]}
UPDATE
Since there will always be one lat/long, you should update your POJO so that geo_location is a single GeoSpatial object, not a List<GeoSpatial>

Related

Error when creating a pagination with apex

No errors on the apex class screen. An unexpected error occurs when you press the search button.
I got an error when I added the pagination code in the second half.
There was no problem before that.
Why?
public with sharing class AccountListCon {
static List<String> TARGET_FIELDS = new List<String>{
'Name'
};
public SearchCondition condition{ get;set; }
public List<AccountList__c> results { get;set; }
public String sortingField { get;set; }
public void init(){
this.condition = new SearchCondition();
this.results = new List<AccountList__c>();
}
public PageReference clear(){
init();
return null;
}
public PageReference search() {
if( condition.validate() ){
return null;
}
String soqlQuery = condition.getSoqlQuery();
System.debug('[soql] ' + soqlQuery);
try{
this.results = database.query(soqlQuery);
System.debug(this.results);
}catch(DmlException e){
ApexPages.addMessages(e);
System.debug('[DmlException]' + e);
}catch(Exception e){
ApexPages.addMessages(e);
System.debug('[Exception]' + e);
}
return null;
}
public PageReference sort(){
if(this.sortingField == null ){
return null;
}
if(this.sortingField == this.condition.sortkey){
this.condition.setOrderReverse();
}
else {
this.condition.sortkey = this.sortingField;
}
search();
return null;
}
public Class SearchCondition {
private Time JST_AM0 = Time.newInstance(9, 0, 0, 0);
public AccountList__c obj {get;set;}
public SearchCondition() {
this.obj = new AccountList__c();
sortkey = 'LastModifiedDate';
order = 'DESC';
}
public String getSoqlQuery(){
List<String> param = new String[]{ getFieldList(), getWhere(), getOrder() };
return String.format('SELECT {0} FROM AccountList__c {1} {2} LIMIT 500', param);
}
private String getFieldList(){
return String.join(TARGET_FIELDS, ',');
}
private String getWhere(){
List<String> param = new String[]{ };
--Omission--
if(param.isEmpty()){
return '';
}
return 'WHERE ' + String.join(param, ' AND ');
}
private String getOrder(){
List<String> param = new String[]{ sortkey, order };
return String.format('ORDER BY {0} {1}', param);
}
private DateTime adjustJSTtoGMS(DateTime day){
JST_AM0 = Time.newInstance(15, 0, 0, 0);
return Datetime.newInstance(day.date(), JST_AM0);
}
--Omission--
private static final Integer PAGE_SIZE = 10;
public Integer currentPage {get; set;}
public Integer totalPage {get; set;}
private ApexPages.StandardSetController ssController;
public Boolean getEnablePrev(){
return ssController.getHasPrevious();
}
public Boolean getEnableNext(){
return ssController.getHasNext();
}
public void PagingCtrl(){
}
public PageReference searchinit() {
ssController = new ApexPages.StandardSetController([SELECT Id, Name FROM Account]);
currentPage = ssController.getPageNumber();
ssController.setPageSize(PAGE_SIZE);
totalPage = (Integer)Math.ceil((Decimal)ssController.getResultSize() / PAGE_SIZE);
return null;
}
public void next() {
ssController.next();
currentPage = ssController.getPageNumber();
}
public void prev() {
ssController.previous();
currentPage = ssController.getPageNumber();
}
public List<Account> getAccountList(){
return (List<Account>)ssController.getRecords();
}
}
Attempt to de-reference a null object
FATAL_ERROR Class.AccountListCon.getEnablePrev: line 292, column 1
public Boolean getEnablePrev(){
return ssController.getHasPrevious();
}
It looks like getEnablePrev() is being called prior to searchInit(), where ssController is initialized. Your Visualforce page may be attempting to render the pagination area prior to completing the initialization of the required data; we couldn't tell the reason why without seeing the relevant portions of your Visualforce page.

JavaFX - How do I access the result(ObservableList) from a service?

How do I access the returned result from a service? The result is queried from the database and added to a ObservableList. I have a checkbox and wanted its value to depend on the result from the database.
How do I bind the checkbox so that its value(checked/unchecked) will depend on the rs.getString("studentForm137") field.
//cboxForm137.selectedProperty().bind(//I don't know the codes to bind checkbox);
Service
final Service<ObservableList<Student>> service = new Service<ObservableList<Student>>()
{
#Override
protected Task<ObservableList<Student>> createTask()
{
return new Task<ObservableList<Student>>()
{
#Override
protected ObservableList<Student> call() throws Exception
{
for (int i = 0; i < 250; i++)
{
updateProgress(i, 250);
Thread.sleep(2);
}
return student.display();
}
};
}
};
service.start();
Student Class
public class Student extends Person {
private SimpleStringProperty form137;
private SimpleStringProperty form138;
private SimpleStringProperty goodMoralCertificate;
private SimpleStringProperty birthCertificate;
private SimpleStringProperty highschoolDiploma;
public Student()
{
super();
}
public Student(String lastName, String firstName, String middleName,
String cpNumber, String address, String dateOfBirth,
String placeOfBirth, String emailAddress, String gender,
String fathersName, String mothersName,
String form137, String form138, String goodMoralCertificate,
String birthCertificate, String highschoolDiploma)
{
super(lastName, firstName, middleName,
cpNumber, address, dateOfBirth, placeOfBirth, emailAddress, gender,
fathersName, mothersName);
this.form137 = new SimpleStringProperty(form137);
this.form138 = new SimpleStringProperty(form138);
this.goodMoralCertificate = new SimpleStringProperty(goodMoralCertificate);
this.birthCertificate = new SimpleStringProperty(birthCertificate);
this.highschoolDiploma = new SimpleStringProperty(highschoolDiploma);
}
//form137
public String getForm137()
{
return form137.get();
}
public void setForm137(String form137)
{
this.form137.set(form137);
}
public StringProperty form137Property()
{
return form137;
}
//form138
public String getForm138()
{
return form138.get();
}
public void setForm138(String form138)
{
this.form138.set(form138);
}
public StringProperty form138Property()
{
return form138;
}
//goodMoralCertificate
public String getGoodMoralCertificate()
{
return goodMoralCertificate.get();
}
public void setGoodMoralCertificate(String goodMoralCertificate)
{
this.goodMoralCertificate.set(goodMoralCertificate);
}
public StringProperty goodMoralCertificateProperty()
{
return goodMoralCertificate;
}
//birthCertificate
public String getBirthCertificate()
{
return birthCertificate.get();
}
public void setBirthCertificate(String birthCertificate)
{
this.birthCertificate.set(birthCertificate);
}
public StringProperty birthCertificateProperty()
{
return birthCertificate;
}
//highschoolDiploma
public String getHighschoolDiploma()
{
return highschoolDiploma.get();
}
public void setHighschoolDiploma(String highschoolDiploma)
{
this.highschoolDiploma.set(highschoolDiploma);
}
public StringProperty highschoolDiplomaProperty()
{
return highschoolDiploma;
}
#Override
public ObservableList display()
{
Connection c = null;
PreparedStatement pst = null;
ResultSet rs = null;
ObservableList<Student> student = FXCollections.observableArrayList();
try
{
c = MySqlConnection.connect();
String SQL = "SELECT * " +
"FROM students ";
pst = c.prepareStatement(SQL);
rs = pst.executeQuery();
while(rs.next())
{
student.add(new Student(rs.getString("studentLastName"),
rs.getString("studentFirstName"),
rs.getString("studentMiddleName"),
rs.getString("studentCPNumber"),
rs.getString("studentAddress"),
rs.getString("studentDateOfBirth"),
rs.getString("studentPlaceOfBirth"),
rs.getString("studentEmailAddress"),
rs.getString("studentGender"),
rs.getString("studentFathersName"),
rs.getString("studentMothersName"),
rs.getString("studentForm137"),
rs.getString("studentForm138"),
rs.getString("studentGMC"),
rs.getString("studentNSO"),
rs.getString("studentHSDiploma")));
}
}
catch(Exception e)
{
System.out.println("Error on Building Data");
}
finally
{
try
{
PublicClass.closeConnection(c, pst, rs);
}
catch (SQLException ex)
{
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
}
return student;
}
}

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 6 column 11 path $.data

i have json, and i want to retrieve using gson,below my json :
{
"status_code":1,
"message":"response ok",
"api_version":"v1",
"api_endpoint_name":"category_island",
"data": [
{
"island_id":1,
"island_name":"Anambas",
"categories": [
{"id":1, "category_name":"Culinary"},
{"id":2, "category_name":"Hotel"},
{"id":3, "category_name":"Culture"}
]
}
]
}
after that i create model to retrieve it :
public class ModelCategory {
#SerializedName("status_code")
public String status_code;
#SerializedName("message")
public String message;
#SerializedName("api_version")
public String api_version;
#SerializedName("api_endpoint_name")
public String api_endpoint_name;
#SerializedName("data")
public data data;
public static class data {
#SerializedName("id")
public String id;
#SerializedName("island_name")
public String island_name;
#SerializedName("categories")
public List<categories> categories;
public static class categories {
#SerializedName("ID")
public String id;
#SerializedName("category_name")
public String category_name;
}
}
}
and this is my code to retrieve json, i'm using gson:
ModelCategory model = new Gson().fromJson(models, ModelCategory.class);
ArrayList<ModelCategory.data.categories> _model = (ArrayList<ModelCategory.data.categories>) model.data.categories;
but when i run always display error in ModelCategory , error like below :
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 6 column 11 path $.data
You need to change the model. Try this -
Category.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Category {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("category_name")
#Expose
private String categoryName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
#Override
public String toString() {
return "Category [id=" + id + ", categoryName=" + categoryName + "]";
}
}
Datum.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Datum {
#SerializedName("island_id")
#Expose
private Integer islandId;
#SerializedName("island_name")
#Expose
private String islandName;
#SerializedName("categories")
#Expose
private List<Category> categories = new ArrayList<Category>();
public Integer getIslandId() {
return islandId;
}
public void setIslandId(Integer islandId) {
this.islandId = islandId;
}
public String getIslandName() {
return islandName;
}
public void setIslandName(String islandName) {
this.islandName = islandName;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
#Override
public String toString() {
return "Datum [islandId=" + islandId + ", islandName=" + islandName
+ ", categories=" + categories + "]";
}
}
Example.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("status_code")
#Expose
private Integer statusCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("api_version")
#Expose
private String apiVersion;
#SerializedName("api_endpoint_name")
#Expose
private String apiEndpointName;
#SerializedName("data")
#Expose
private List<Datum> data = new ArrayList<Datum>();
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public String getApiEndpointName() {
return apiEndpointName;
}
public void setApiEndpointName(String apiEndpointName) {
this.apiEndpointName = apiEndpointName;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
#Override
public String toString() {
return "Example [statusCode=" + statusCode + ", message=" + message
+ ", apiVersion=" + apiVersion + ", apiEndpointName="
+ apiEndpointName + ", data=" + data + "]";
}
}
Now you can test it as -
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Example;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* #param args
*/
public static void main(String[] args) {
String s = "{\"status_code\":1,\"message\":\"response ok\",\"api_version\":\"v1\",\"api_endpoint_name\":\"category_island\",\"data\":[{\"island_id\":1,\"island_name\":\"Anambas\",\"categories\":[{\"id\":1,\"category_name\":\"Culinary\"},{\"id\":2,\"category_name\":\"Hotel\"},{\"id\":3,\"category_name\":\"Culture\"}]}]}";
Example info = gson.fromJson(s, Example.class);
System.out.println(info);
}
}
Result is -
Example [statusCode=1, message=response ok, apiVersion=v1, apiEndpointName=category_island, data=[Datum [islandId=1, islandName=Anambas, categories=[Category [id=1, categoryName=Culinary], Category [id=2, categoryName=Hotel], Category [id=3, categoryName=Culture]]]]]

How to print a specific object by field id within an array list of objects?

I have a Location class that stores multiple location objects, parsed in from a JSON file. At the moment I can print out all locations in the list by using the toString() method. The output looks like this:
http://hastebin.com/eruxateduz.vhdl
This is an example of one of the loctions within the list:
Location [location=null, id=3, description=You are at battlefield of Jerusalem. You are in awe of your surroundings, you see an exit to the west., weight=100, name=Jerusalem, exit=[Exit [title=Hattin, direction=West]]],
But I'm wondering how I can print out a specific location within that list by the field value id, for example the loction with id="2"?
I'm thinking an override toString method could be created to take an input of id, and print the corresponding location object, but not sure how to print by 'id':
if(LocationObject.getId() == "2") {
//do something
}
This is the POJO Location class that stores the objects:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}
try checking id's
if(LocationObject.getId() == "2") {
System.out.println(LocationObject.getDescription());
}

JPA, error in meta-data for CLASS: more than one primary key field

I have a parent and a child class. When I run the app I'm getting following error:
Error in meta-data for com.twitterjaya.model.HistoryDeviceJPA: More than one primary key field.
I have no idea why it says I defined more than one primary key. Any suggestion would be appreciated.
#Entity(name = "HistoryJPA")
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
#DiscriminatorValue("HistoryJPA")
public class HistoryJPA {
#Id
String pageAddress;
String domain;
String pageTitle;
long pageVisits;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HistoryJPA that = (HistoryJPA) o;
if (!pageAddress.equals(that.pageAddress)) return false;
return true;
}
#Override
public int hashCode() {
return pageAddress.hashCode();
}
#Override
public String toString() {
return "HistoryJPA{" +
"pageAddress='" + pageAddress + '\'' +
", domain='" + domain + '\'' +
", pageTitle='" + pageTitle + '\'' +
", pageVisits=" + pageVisits +
'}';
}
public String getPageAddress() {
return pageAddress;
}
public void setPageAddress(String pageAddress) {
this.pageAddress = pageAddress;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getPageTitle() {
return pageTitle;
}
public void setPageTitle(String pageTitle) {
this.pageTitle = pageTitle;
}
public long getPageVisits() {
return pageVisits;
}
public void setPageVisits(long pageVisits) {
this.pageVisits = pageVisits;
}
}
and child class:
#Entity(name = "HistoryDeviceJPA")
#DiscriminatorValue("HistoryDeviceJPA")
public class HistoryDeviceJPA extends HistoryJPA {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userUUID;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
HistoryDeviceJPA that = (HistoryDeviceJPA) o;
if (!id.equals(that.id)) return false;
if (!userUUID.equals(that.userUUID)) return false;
return true;
}
#Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + id.hashCode();
result = 31 * result + userUUID.hashCode();
return result;
}
#Override
public String toString() {
return "HistoryDeviceJPA{" +
"id=" + id +
", userUUID='" + userUUID + '\'' +
'}';
}
public String getUserUUID() {
return userUUID;
}
public void setUserUUID(String userUUID) {
this.userUUID = userUUID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
As explained by the error message, you have two primary keys (annotated with #Id):
one in HistoryJPA on field pageAddress
one in HistoryDeviceJPA on field id
You should get rid of one of them, or create a composite primary key depending on your needs.

Resources