Why are my properties unrecognizable when converting to pojo [duplicate] - java

This question already has answers here:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field
(7 answers)
Closed 5 years ago.
I have the following JSON:
{ "_id" : "3", "longitude" : "3222", "latitude" : "55", "timeDateOfUsage" : ["02/11/17 13:30:35", "1", "02/11/17 13:30:45", "1", "02/11/17 13:30:51", "0"] }
I'm trying to convert it to a pojo using jackson. This is what I have:
String inputJson = "{ \"_id\" : \"3\", \"longitude\" : \"3222\",
\"latitude\" : \"55\", \"timeDateOfUsage\" : [\"02/11/17 13:30:35\", \"1\", \"02/11/17 13:30:45\", \"1\", \"02/11/17 13:30:51\", \"0\"] }";
ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try{
dbResponseonce response = mapper.readValue(inputJson,dbResponseonce.class);
System.out.println(response.getLatitude());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And my other class has fields which are named as the elements in the JSON and has getters and setters.
The above code works however it does not work when I just create a basic ObjectMapper object with no configurations. Why is this? This is the stacktrace error:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "_id" (Class dbResponseonce), not marked as ignorable
This is my pojo class that has the getters and setters:
public class dbResponseonce {
private String _id;
public String getId() { return this._id; }
public void setId(String _id) { this._id = _id; }
private String longitude;
public String getLongitude() { return this.longitude; }
public void setLongitude(String longitude) { this.longitude = longitude; }
private String latitude;
public String getLatitude() { return this.latitude; }
public void setLatitude(String latitude) { this.latitude = latitude; }
private ArrayList<String> timeDateOfUsage;
public ArrayList<String> getTimeDateOfUsage() { return this.timeDateOfUsage; }
public void setTimeDateOfUsage(ArrayList<String> timeDateOfUsage) { this.timeDateOfUsage = timeDateOfUsage; }}

Your getter and setter for _id is incorrect.
Try defining them as follows:
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
Or use on the getter or setter of _id #JsonProperty("_id")

Related

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

Ok, So I read a couple other questions with this same error, but none have been answered as working, and doesnt seem like I can get it working.
I am connecting to google in-app billing and have everything set up, but, when I try to pull my skudetails (I have 2 SKUs there now), I get the error -
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I have a SubscriptionActivity, Result (serializable), and Details model class (serializable). Below is the code, any help will be great, thanks-
From subscriptionactivity:
Gson gson = new Gson();
try {
Result result = gson.fromJson(skuDetailsList.toString(), Result.class);
if (result != null) {
for (Details d : result.getDetails()) {
System.out.println(d.getProductId()
+ " \n " + d.getTitle() + " \n " + d.getDescription() + " \n "
+ d.getPrice());
}
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
From details model:
public class Details implements Serializable{
#SerializedName("productId")
#Expose
private String productId;
#SerializedName("type")
#Expose
private String type;
#SerializedName("price")
#Expose
private String price;
#SerializedName("price_amount_micros")
#Expose
private Integer priceAmountMicros;
#SerializedName("price_currency_code")
#Expose
private String priceCurrencyCode;
#SerializedName("subscriptionPeriod")
#Expose
private String subscriptionPeriod;
#SerializedName("freeTrialPeriod")
#Expose
private String freeTrialPeriod;
#SerializedName("title")
#Expose
private String title;
#SerializedName("description")
#Expose
private String description;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Integer getPriceAmountMicros() {
return priceAmountMicros;
}
public void setPriceAmountMicros(Integer priceAmountMicros) {
this.priceAmountMicros = priceAmountMicros;
}
public String getPriceCurrencyCode() {
return priceCurrencyCode;
}
public void setPriceCurrencyCode(String priceCurrencyCode) {
this.priceCurrencyCode = priceCurrencyCode;
}
public String getSubscriptionPeriod() {
return subscriptionPeriod;
}
public void setSubscriptionPeriod(String subscriptionPeriod) {
this.subscriptionPeriod = subscriptionPeriod;
}
public String getFreeTrialPeriod() {
return freeTrialPeriod;
}
public void setFreeTrialPeriod(String freeTrialPeriod) {
this.freeTrialPeriod = freeTrialPeriod;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
From Result activity:
public class Result implements Serializable{
#SerializedName("SkuDetails")
#Expose
private ArrayList<Details> details = new ArrayList<Details>();
/**
*
* #return The SkuDetails
*/
public ArrayList<Details> getDetails() {
return details;
}
/**
*
* #param details
* The details
*/
public void setDetails(ArrayList<Details> details) {
this.details = details;
}
}*
Oh..and the response I was trying to parse (skuDetailsList.toString()) is:
[
SkuDetails: {
"productId": "basic_sub",
"type": "subs",
"price": "$0.99",
"price_amount_micros": 990000,
"price_currency_code": "USD",
"subscriptionPeriod": "P1M",
"freeTrialPeriod": "P4W2D",
"title": "Basic Subscription Service (DadBod Recipes)",
"description": "Basic Subscription Service for DadBodRecipes"
},
SkuDetails: {
"productId": "enterprise_sub",
"type": "subs",
"price": "$2.99",
"price_amount_micros": 2990000,
"price_currency_code": "USD",
"subscriptionPeriod": "P1M",
"freeTrialPeriod": "P4W2D",
"title": "Enterprise Subscription Service (DadBod Recipes)",
"description": "Enterprise Subscription Service for DadBodRecipes"
}
]
Issue is because, the result you're getting is as <Key-Value> pair (not as JSON object/Array, but similar to it).
So you'll need to make it to JSONObject first and then parse it using Gson like below:
Map<String, String> params = skuDetailsList;
JSONObject object = new JSONObject(params);
Result result = gson.fromJson(object.toString(), Result.class);
Do like this, hope it helps !
You are trying to parse your json
[
as
{
when you see the [ it represents a list
when you see the { it represents an object.
I'm pretty sure you know that as you built a wrapper class, but your wrapper class is also an object, not an array.
So your choices are to have your wrapper class extend ArrayList or some form of List.
Or
Tell your Json converter that the base is an Array and you want the first object in the list is an object of your type.

Jackson objectmapper deserializing null string to "null" value

Sometimes during deserialization the null is getting converted to "null". Is there a way I can avoid this?
{
"item" : {
"title": "null",
"id" : "134df"
}
}
I want it as
{
"item" : {
"title": null,
"id" : "134df"
}
}
or
{
"item" : {
"title": "",
"id": "134df"
}
}
You can achieve it by using Google JSON i.e gson.
If you are setting null against the title, then while converting the Object to JSON at that time title will not be available in the JSON string.
After that you can check a condition whether the object is available or not in the JSON and do the further task.
Here is the code spinet.
import com.google.gson.Gson;
public class JackSonObjectMapperExample {
public static void main(String[] args){
Item item = new Item();
item.setId("134df");
item.setTitle(null);
POJOExample pojo = new POJOExample();
pojo.setItem(item);
Gson gson = new Gson();
String jsonInString = gson.toJson(pojo);
System.out.println("=================>>"+jsonInString);
}
}
class POJOExample{
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
class Item{
private String title;
private String id;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
output:
=================>>{"item":{"id":"134df"}}
Hope, this will help you.

Looping through Multiple JSON Objects in Android

I'm trying to parse a JSON object, part of which looks like this :
{
"status":{
"rcode":200,
"message":"OK"
},
"data":{
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
"1 "{
"SubFranchiseID":"1",
"OutletID":"60",
"OutletName":"Bill ",
.
.
.
}
}
There are nearly 35 Json objects and nested JsonArrays for each of these objects.I'm trying to get data like this :
url = new URL(uri);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json =sb.toString();
JSONObject sjson=json.getJSONObject("data");
Log.d("sjson values-->",sjson+"--");
**JSONObject ssjson=sjson.getJSONObject("0");**
And now i am getting each of values like this :
String outletName = ssjson.getString("OutletName");
My question is there any better way (loop) through all objects ( 0,1,...35) and get data for each individual object separately.
Example json
{
"status": {
"rcode": "200",
"message": "Good, you got me!!!"
},
"data": [
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill",
},
{
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill"
}
]
}
Represent the json in terms of plain java classes with getter and
setters
First create a the root class (for the root object)
public class Root {
//For the status object
private Status status;
//For the array of data objects
private List<Data> data;
//create setters and getters for the two properties.
}
public class Status {
private String rcode;
//this maps to the rcode in the status object in json
private String message;
//create setters and getters for the two
}
public class Data {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
//create setters and getters for these properties.
}
Now, lets do the magic with gson (The serialization of the json in to the ready made classes)
reader.close();
json =sb.toString();
Root root = new Gson().fromJson(response, Root.class);
//get the rcode
if(root.getStatus().getrCode().equalsIgnoreCase("200"))
{
//print the data.
for(Data d : root.getData()) {
System.out.println(d.getSubFranchiseID()+"-"+d.getOutletID()+"-"+d.getOutletName());
}
}
A small note for using gson.
1.) The property names inside the classes should match the property in the json or else use a `#SerializeName("propertyname")`.
2.) An array of objects would map to List<YourObject> , for eg : the data property in the json.
3.) You can have default value for your properties without creating getters and setters for them like
private boolean isJson = true;
Thanks for the help. I have a lot of json objects inside "data" -> "0" like "Outletname","OutletID ",etc , before Json Array ( "Categories" ). i have created a model class for my data. Now i want to itterate json objects data using Gson.Part of my json data
"0":{
"SubFranchiseID":"0",
"OutletID":"607",
"OutletName":"Spill ",
"BrandID":"403",
"Address":"J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India",
"NeighbourhoodID":"1",
"CityID":"1",
"Email":null,
"Timings":"Everyday: 6 pm to 1:30 am.",
"CityRank":null,
"Latitude":"19.127473",
"Longitude":"72.832545",
"Pincode":null,
"Landmark":null,
"Streetname":null,
"BrandName":"Spill ",
"OutletURL":"https:\/\/plus.google.com\/111539701326240643109\/about?hl=en-US",
"NumCoupons":1,
"NeighbourhoodName":"Andheri West",
"PhoneNumber":"+91 22 2642 5895",
"CityName":"Mumbai",
"Distance":8205.2235,
"Categories":[
{
"OfflineCategoryID":"32",
"Name":"Continental",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"13",
"Name":"Bar and Restaurant",
"ParentCategoryID":"1",
"CategoryType":"TypeOfRestaurant"
},
{
"OfflineCategoryID":"17",
"Name":"Italian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
},
{
"OfflineCategoryID":"1",
"Name":"Restaurant",
"ParentCategoryID":null,
"CategoryType":""
},
{
"OfflineCategoryID":"21",
"Name":"North Indian",
"ParentCategoryID":"1",
"CategoryType":"Cuisine"
}
],
"LogoURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/logo_403.jpg",
"CoverURL":"http:\/\/www.google.in\/sitespecific\/media\/generated\/offlineimages\/cover_607.jpg"
},
}
My java Model Class :
/**
* SubFranchiseID : 0
* OutletID : 607
* OutletName : Spill
* BrandID : 403
* Address : J-349, JP Road, Opp. Apna Bazar, JP Rd, D.N.Nagar, Andheri West, Mumbai, Maharashtra, India
* NeighbourhoodID : 1
* CityID : 1
* Email : null
* Timings : Everyday: 6 pm to 1:30 am.
* CityRank : null
* Latitude : 19.127473
* Longitude : 72.832545
* Pincode : null
* Landmark : null
* Streetname : null
* BrandName : Spill
* OutletURL : https://plus.google.com/111539701326240643109/about?hl=en-US
* NumCoupons : 1
* NeighbourhoodName : Andheri West
* PhoneNumber : +91 22 2642 5895
* CityName : Mumbai
* Distance : 8205.2235
* Categories : [{"OfflineCategoryID":"32","Name":"Continental","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"13","Name":"Bar and Restaurant","ParentCategoryID":"1","CategoryType":"TypeOfRestaurant"},{"OfflineCategoryID":"17","Name":"Italian","ParentCategoryID":"1","CategoryType":"Cuisine"},{"OfflineCategoryID":"1","Name":"Restaurant","ParentCategoryID":null,"CategoryType":""},{"OfflineCategoryID":"21","Name":"North Indian","ParentCategoryID":"1","CategoryType":"Cuisine"}]
* LogoURL : http://www.google.in/sitespecific/media/generated/offlineimages/logo_403.jpg
* CoverURL : http://www.google.in/sitespecific/media/generated/offlineimages/cover_607.jpg
*/
public static class OutletDetailsEntity {
private String SubFranchiseID;
private String OutletID;
private String OutletName;
private String BrandID;
private String Address;
private String NeighbourhoodID;
private String CityID;
private Object Email;
private String Timings;
private Object CityRank;
private String Latitude;
private String Longitude;
private Object Pincode;
private Object Landmark;
private Object Streetname;
private String BrandName;
private String OutletURL;
private int NumCoupons;
private String NeighbourhoodName;
private String PhoneNumber;
private String CityName;
private double Distance;
private String LogoURL;
private String CoverURL;
private List<CategoriesEntity> Categories;
public void setSubFranchiseID(String SubFranchiseID) {
this.SubFranchiseID = SubFranchiseID;
}
public void setOutletID(String OutletID) {
this.OutletID = OutletID;
}
public void setOutletName(String OutletName) {
this.OutletName = OutletName;
}
public void setBrandID(String BrandID) {
this.BrandID = BrandID;
}
public void setAddress(String Address) {
this.Address = Address;
}
public void setNeighbourhoodID(String NeighbourhoodID) {
this.NeighbourhoodID = NeighbourhoodID;
}
public void setCityID(String CityID) {
this.CityID = CityID;
}
public void setEmail(Object Email) {
this.Email = Email;
}
public void setTimings(String Timings) {
this.Timings = Timings;
}
public void setCityRank(Object CityRank) {
this.CityRank = CityRank;
}
public void setLatitude(String Latitude) {
this.Latitude = Latitude;
}
public void setLongitude(String Longitude) {
this.Longitude = Longitude;
}
public void setPincode(Object Pincode) {
this.Pincode = Pincode;
}
public void setLandmark(Object Landmark) {
this.Landmark = Landmark;
}
public void setStreetname(Object Streetname) {
this.Streetname = Streetname;
}
public void setBrandName(String BrandName) {
this.BrandName = BrandName;
}
public void setOutletURL(String OutletURL) {
this.OutletURL = OutletURL;
}
public void setNumCoupons(int NumCoupons) {
this.NumCoupons = NumCoupons;
}
public void setNeighbourhoodName(String NeighbourhoodName) {
this.NeighbourhoodName = NeighbourhoodName;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public void setCityName(String CityName) {
this.CityName = CityName;
}
public void setDistance(double Distance) {
this.Distance = Distance;
}
public void setLogoURL(String LogoURL) {
this.LogoURL = LogoURL;
}
public void setCoverURL(String CoverURL) {
this.CoverURL = CoverURL;
}
public void setCategories(List<CategoriesEntity> Categories) {
this.Categories = Categories;
}
public String getSubFranchiseID() {
return SubFranchiseID;
}
public String getOutletID() {
return OutletID;
}
public String getOutletName() {
return OutletName;
}
public String getBrandID() {
return BrandID;
}
public String getAddress() {
return Address;
}
public String getNeighbourhoodID() {
return NeighbourhoodID;
}
public String getCityID() {
return CityID;
}
public Object getEmail() {
return Email;
}
public String getTimings() {
return Timings;
}
public Object getCityRank() {
return CityRank;
}
public String getLatitude() {
return Latitude;
}
public String getLongitude() {
return Longitude;
}
public Object getPincode() {
return Pincode;
}
public Object getLandmark() {
return Landmark;
}
public Object getStreetname() {
return Streetname;
}
public String getBrandName() {
return BrandName;
}
public String getOutletURL() {
return OutletURL;
}
public int getNumCoupons() {
return NumCoupons;
}
public String getNeighbourhoodName() {
return NeighbourhoodName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public String getCityName() {
return CityName;
}
public double getDistance() {
return Distance;
}
public String getLogoURL() {
return LogoURL;
}
public String getCoverURL() {
return CoverURL;
}

converting JSONObject to Object list

I want to convert a JSONObject (array) to a list of Objects.
As I am very new with java i am having quite some problems.
JSON:
"products": [
{
"pid": "0",
"name": "Product Na",
"kategorie": "Category",
"beschreibung": "Description",
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
{
"pid": "1160",
"name": "Beispiel B",
"kategorie": null,
"beschreibung": null,
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
Product class:
public class Produkt {
public String id;
public String name;
public String categorie;
public String description;
public String image;
public double price;
}
I have tried several things with gson, but ultimately nothing worked.
I don't need a working code, just a hint on how to deserialize the JSON by the tags.
I hope you can help me. Thanks in advance!
Considering that your request or string data is in JSONObject jsonArray. Below code can help you get the response in List using TypeToken.
JSONArray jsonArray = jsonResponse.getJSONArray("products");
String newList = jsonArray.toString();
Gson gson = new Gson();
Type typeOfProduktList = new TypeToken<ArrayList<Produkt>>() {}.getType();
List<Produkt> finalList = gson.fromJson(newList, typeOfProduktList);
Now, you can return the finalList in the end or process it as per your wish.
Try creating a class that has a list of products. Here is a complete example:
Add brackets around your json data like this:
{
"products": [
{
"pid": "0",
"name": "Product Na",
"kategorie": "Category",
"beschreibung": "Description",
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
},
{
"pid": "1160",
"name": "Beispiel B",
"kategorie": null,
"beschreibung": null,
"bild": "http:\/\/arsdecora.net\/wp-content\/uploads\/2015\/04\/B1696.jpg",
"preis": "0"
}
]
}
Here are the classes you need:
Data class:
public class Data {
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
Product class:
public class Product {
private String pid;
private String name;
private String kategorie;
private String beschreigung;
private String bild;
private String preis;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKategorie() {
return kategorie;
}
public void setKategorie(String kategorie) {
this.kategorie = kategorie;
}
public String getBeschreigung() {
return beschreigung;
}
public void setBeschreigung(String beschreigung) {
this.beschreigung = beschreigung;
}
public String getBild() {
return bild;
}
public void setBild(String bild) {
this.bild = bild;
}
public String getPreis() {
return preis;
}
public void setPreis(String preis) {
this.preis = preis;
}
}
GsonTest class:
public class GsonTest {
public static void main(String[] args) {
Gson gson = new Gson();
Object obj;
try {
JsonParser parser = new JsonParser();
obj = parser.parse(new FileReader("C:\data.json"));
JsonObject jsonObject = (JsonObject) obj;
Data data = gson.fromJson(jsonObject, Data.class);
} catch (JsonIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Exception in JSON parsing: Expected BEGIN_ARRAY but was BEGIN_OBJECT?

I am trying to parse the JSON response from this link and I'm getting this exception:
Expected BEGIN_ARRAY but was BEGIN_OBJECT
I have created this class to encapsulate the JSON data:
public class PlacesTextSearch {
private String icon;
private String name;
private String types;
private String formatted_address;
private double latitude;
private double longitude;
private String id;
public PlacesTextSearch(String icon,String name,String types,String formatted_address,double latitude,double longitude) {
// TODO Auto-generated constructor stub
setIcon(icon);
setName(name);
setTypes(types);
setFormatted_address(formatted_address);
setLatitude(latitude);
setLongitude(longitude);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getFormatted_address() {
return formatted_address;
}
public void setFormatted_address(String formatted_address) {
this.formatted_address = formatted_address;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
And this is my code to parse the JSON:
private ArrayList<PlacesTextSearch> arrayListPlaces;
Type listType = new TypeToken<ArrayList<PlacesTextSearch>>(){}.getType();
arrayListPlaces=new Gson().fromJson(response,listType);
Here you can see the complete exception stacktrace:
Have you read Gson documentation before trying to write your code? Have you even taken a look at JSON structures?
Your code has many errors... The point is that you have to create a Java class structure that matches your JSON structure. And in fact, your class structure is not even similar to the JSON you want to parse! Basically where there's an object { } in your JSON you have to use a class, and where there's an array in your JSON [ ] you have to use an array or a List...
According to your PlacesTextSearch class, I guess the JSON piece you want to parse is:
{
...,
"results" : [
{
"formatted_address" : "Zeytinlik Mh., Bakırköy/İstanbul, Türkiye",
"geometry" : {
"location" : {
"lat" : 40.9790040,
"lng" : 28.8730110
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "e520b6e19bae5c014470989f9d3405e55dce5155",
"name" : "PTT",
"types" : [ "post_office", "finance", "establishment" ]
...
},
...
],
...
}
So, how do you pretend to parse this into an ArrayList<PlacesTextSearch>!? That's not what your JSON represents! Do you really not see it?
Try something like this class structure (pseudo-code):
class Response
List<PlacesTextSearch> results;
class PlacesTextSearch
String formatted_address;
Geometry geometry;
String icon;
String id;
String name;
List<String> types;
class Geometry
Location location;
class Location
long lat;
long lng;
And parse it with:
Response response = new Gson().fromJson(response, Response.class);

Categories