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

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());
}

Related

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]]]]]

GSON fromJSON having problems

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>

Passing parameters using the PUT method

I defined an endpoint with the following methods:
#ApiMethod(name = "update", path = "properties/{id}", httpMethod = HttpMethod.PUT)
public void update(#Named("id") Long id, RealEstatePropertyAPI propertyAPI,
User user) {
On the client side I tried several calls but none of them populates the propertyAPI object on the server side. The instance is created with all fields set to null except the id.
var jsonId = { 'id': '11'};
var x = {"name": "Test","address": { "street": "White House"}};
gapi.client.realestate.update(jsonId, x).execute(function(resp) {
console.log('PropertyEdited');
console.log(resp);
});
Or
var jsonId = { 'id': '11'};
var x = {"name": "Test","address": { "street": "White House"}};
gapi.client.realestate.update(jsonId, {'resource' : x}).execute(function(resp) {
console.log('PropertyEdited');
console.log(resp);
});
The Java classes:
public class RealEstatePropertyAPI {
private Long id;
private String name;
private AddressAPI address;
public RealEstatePropertyAPI() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public AddressAPI getAddress() {
return address;
}
public void setAddress(AddressAPI address) {
this.address = address;
}
}
public class AddressAPI {
private Long id;
private String street;
private String city;
private String state;
private String zip;
private String country;
public AddressAPI() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
I'm not actually sure about about this, but you can try to pass all the parameters within a single object, I mean wrap the parameters with brackets { }, like this:
//var jsonId = { 'id': '11'};
var x = {"name": "Test","address": { "street": "White House"}};
gapi.client.realestate.update({'id': '11', 'resource' : x}).execute(function(resp) {
console.log('PropertyEdited');
console.log(resp);
});
Because in fact in both your requests you're sending 2 objects... And I think you have to use 'resource' for the parameters in the POST data as in your second option...

JAVA Google App Engine + Facebook API + GSON = Trouble with Javabean

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.

Resources