How to get data from [Object] android - java

I am getting this response from my Express API Call.
Here's the Response:
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [{
"topicName": "1.1 Introduction",
"topicURL": ""
},
{
"topicName": "1.2 Square Matrix",
"topicURL": ""
}
],
"2": [{
"topicName": "2.1 Numbers",
"topicURL": ""
}
]
}
}]
}
I got the response by using Retrofit in Android. It works great.But it can't parse Objects
Here's my Problem in Android Side.
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [[Object],
[Object]
],
"2": [[Object]
]
}
}]
}
Its showing Object instead of my Data. How to fix this
Here's the Code:
System.out.println(response.body().getResponseData())
String received_data = response.body().getResponseData();
received_data_sub_units_topics_json = new JSONArray("["+received_data+"]");
System.out.println("MAIN2 "+received_data_sub_units_topics_json);
After converting to jsonarray, it shows like this,
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [["Object"],
["Object"]
],
"2": [["Object"]
]
}
}]
}
Please help me with some solutions

For json i always use the library com.fasterxml.jackson.
You can use too org.json.JSONArray, org.json.JSONObject.
Here is an example of each one:
1- jackson
For implements this (is a bit long but you will convert it to java classes, so, you will can edit the values and obtain it more easily than if you use JSONObject), you have to create classes wich has the same structure than your json:
public class principalClass {
ArrayList<ResponseData> responseData;
...
//Getters, setters and constructors
}
public class ResponseData {
public ArrayList<String> unitNames;
public String subject;
public UnitTopics unitTopics;
...
//Getters, setters and constructors
}
public class UnitTopics {
public ArrayList<Topics> first;
public ArrayList<Topics> second;
...
//Getters, setters and constructors
}
public class Topics {
public String topicName;
public String topicURL;
...
//Getters, setters and constructors
}
Something like that, and then you use jackson to pass your json to you class principalClass:
ObjectMapper obj= new ObjectMapper();
PrincipalClass principal= obj.readValue(json, PrincipalClass.class);
The second posibility is to convert the values to JSONArray and JSONObject:
JSONObject bodyJSON = new JSONObject(json);
JSONArray responseData = bodyJSON.getJSONArray("responseData");
JSONArray unitNames= responseData.getJSONArray(0);
JSONObject subject= responseData.getJSONObject(1);
...
And if u want, u can loop through a JSONArray:
for (int i = 0; i < unitNames.length(); i++) {
String element = unitNames.getString(i);
}

You can use gson converter with retrofit to convert your json data to java object model class
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Or you can convert json data to model class like
Gson gson = new Gson();
String jsonInString = "{your json data}";
ResponseModel response= gson.fromJson(jsonInString, ResponseModel.class);

Hey have you tried converting this JSON Object to a POJO.
I'd recommend using:
This website
It saves a lot of time and effort.
These will be your model classes:
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseDatum implements Serializable
{
#SerializedName("unitNames")
#Expose
private List<String> unitNames = null;
#SerializedName("subject")
#Expose
private String subject;
#SerializedName("unitTopics")
#Expose
private UnitTopics unitTopics;
public ResponseDatum() {
}
public ResponseDatum(List<String> unitNames, String subject, UnitTopics unitTopics) {
super();
this.unitNames = unitNames;
this.subject = subject;
this.unitTopics = unitTopics;
}
public List<String> getUnitNames() {
return unitNames;
}
public void setUnitNames(List<String> unitNames) {
this.unitNames = unitNames;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public UnitTopics getUnitTopics() {
return unitTopics;
}
public void setUnitTopics(UnitTopics unitTopics) {
this.unitTopics = unitTopics;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseObject implements Serializable
{
#SerializedName("responseData")
#Expose
private List<ResponseDatum> responseData = null;
public ResponseObject() {
}
public ResponseObject(List<ResponseDatum> responseData) {
super();
this.responseData = responseData;
}
public List<ResponseDatum> getResponseData() {
return responseData;
}
public void setResponseData(List<ResponseDatum> responseData) {
this.responseData = responseData;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UnitTopics implements Serializable
{
#SerializedName("1")
#Expose
private List<com.example.app._1> _1 = null;
#SerializedName("2")
#Expose
private List<com.example.app._2> _2 = null;
public UnitTopics() {
}
public UnitTopics(List<com.example.app._1> _1, List<com.example.app._2> _2) {
super();
this._1 = _1;
this._2 = _2;
}
public List<com.example.app._1> get1() {
return _1;
}
public void set1(List<com.example.app._1> _1) {
this._1 = _1;
}
public List<com.example.app._2> get2() {
return _2;
}
public void set2(List<com.example.app._2> _2) {
this._2 = _2;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _1() {
}
public _1(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _2 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _2() {
}
public _2(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}

Related

Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class java.util.List

I want to read a json file and store it into objects so that I can use it in my logic. After multiple attempts I was able to fetch the json into a Map. But I want the values to be stored in object and not a map.
Below is my code where I tried to fetch it and store in Currency object.
package com.springboot.currencyExchange;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import com.springboot.currencyExchange.model.*;
import com.springboot.currencyExchange.model.Currency;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.springboot.currencyExchange.service.MarketStrategyImpl;
#SpringBootApplication
public class CurrencyExchangeApplication {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
// SpringApplication.run(CurrencyExchangeApplication.class, args);
Object obj = new JSONParser().parse(new FileReader(
"*absolute path*\AvailableMarket.json"));
JSONObject jobj = (JSONObject) obj;
JSONArray ja = (JSONArray) jobj.get("currencies");
Iterator<Currency> itr1 = null;
Iterator<CurrentMarket> itr2 = ja.iterator();
while (itr2.hasNext()) {
itr1 = (Iterator<Currency>) (((List) itr2.next()).iterator());
while (itr1.hasNext()) {
Currency pair = itr1.next();
// System.out.println(pair.getKey() + " : " + pair.getValue());
}
}
}
}
Below is my JSON file
{
"currencies": [
{
"currencyName": "Euro",
"price": 80
},
{
"currencyName": "Pound",
"price": 90
},
{
"currencyName": "USD",
"price": 75
}
],
"trades": [
{
"take": "Euro",
"give": "USD"
},
{
"take": "USD",
"give": "Pound"
}
]
}
Below are the POJO classes I created to store the JSON values:
package com.springboot.currencyExchange.model;
import java.util.List;
public class CurrentMarket {
public List<Currency> currency;
public List<Trade> trade;
public CurrentMarket() {
super();
}
public List<Currency> getCurrency() {
return currency;
}
public void setCurrency(List<Currency> currency) {
this.currency = currency;
}
public List<Trade> getTrade() {
return trade;
}
public CurrentMarket(List<Currency> currency, List<Trade> trade) {
super();
this.currency = currency;
this.trade = trade;
}
#Override
public String toString() {
return "CurrentMarket [currency=" + currency + ", trade=" + trade + "]";
}
public void setTrade(List<Trade> trade) {
this.trade = trade;
}
}
Currency.java
package com.springboot.currencyExchange.model;
import java.io.Serializable;
#SuppressWarnings("serial")
public class Currency implements Serializable{
String currencyName;
Double price;
public String getCurrencyName() {
return currencyName;
}
public void setCurrencyName(String currencyName) {
this.currencyName = currencyName;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Override
public String toString() {
return "Currency [currencyName=" + currencyName + ", price=" + price + "]";
}
public Currency(String currencyName, Double price) {
super();
this.currencyName = currencyName;
this.price = price;
}
}
Trade.java
package com.springboot.currencyExchange.model;
import java.util.ArrayList;
public class Trade {
ArrayList<String> take;
ArrayList<String> give;
public ArrayList<String> getTake() {
return take;
}
public Trade(ArrayList<String> take, ArrayList<String> give) {
super();
this.take = take;
this.give = give;
}
public void setTake(ArrayList<String> take) {
this.take = take;
}
public ArrayList<String> getGive() {
return give;
}
public void setGive(ArrayList<String> give) {
this.give = give;
}
}
I also tried the GSON approach but couldn't fetch it in desired format.
Below is the error message I get with current setup:
Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONObject cannot be cast to class java.util.List (org.json.simple.JSONObject is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')
at com.springboot.currencyExchange.CurrencyExchangeApplication.main(CurrencyExchangeApplication.java:32)
I am not sure how else can I proceed. Any help would be appreciated.
You need to make a few changes at first.
As Abrar Ansari said, change the type of the variables from ArrayList to String in the Trade class. Also rename the currency and trade variables from the CurrencyMarket class to currencies and trades. Make all fields private in all model classes and make sure you have default constructors in all model classes. Then use Jackson's ObjectMapper to deserialize the json file into an object of type CurrentMarket:
ObjectMapper objectMapper = new ObjectMapper();
CurrentMarket currentMarket = objectMapper.readValue(new ClassPathResource("AvailableMarket.json").getFile(),
CurrentMarket.class);

How to read json from google drive with rest api

I have created some Json file that contains shop's objects and i want to store it on Google drive and read it with Retrofit.
Currently, I can't store it in local memory or in-app.
Also, there is no server side yet, so it needs to be stored somewhere that Retrofit can access.
If you have any other ideas, I'd be more than happy to hear.
I make the link public to anyone, and here is my .json file:
{
"shop": [
{
"shopName": "Renuar",
"shopID": "1000",
"isPaid": "false",
"branches": [
{
"branchName": "Branch 1",
"branchPhone": "039599559",
"openingTime": "09:00",
"closingTime": "21:00",
"branchLat": "32.000",
"branchLon": "35.000",
"branchAddressNote": "Grand Canyon"
}
]
},
{
"shopName": "Castro",
"shopID": "1000",
"isPaid": "false",
"branches": [
{
"branchName": "Branch 1",
"branchPhone": "039599559",
"openingTime": "09:00",
"closingTime": "21:00",
"branchLat": "32.000",
"branchLon": "35.000",
"branchAddressNote": "Grand Canyon"
}
]
}
]
}
I've tried the next steps but it's not work for me.
public interface ApiService {
#GET("file/d/1-lsBIzI7Y5uCg8bG_531o49Dcu6E2RdH/view?usp=sharing")
Call<ShopsResponse> getAllShops();
}
public static class RetrofitInstance{
public static Retrofit retrofit = null;
private static final String BASE_URL = "https://drive.google.com/";
public static ApiService getApiService(){
if (retrofit == null){
Gson gson = new GsonBuilder()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit.create(ApiService.class);
}
}
ApiService apiService = RetrofitInstance.getApiService();
apiService.getAllShops().enqueue(new Callback<ShopsResponse>() {
#Override
public void onResponse(Call<ShopsResponse> call, Response<ShopsResponse> response) {
ShopsResponse response1 = response.body();
Log.d(TAG, "onResponse: "+response1.getShop().size());
}
#Override
public void onFailure(Call<ShopsResponse> call, Throwable t) {
Log.d(TAG, "onResponse: "+t.getMessage());
}
});
That what i receive in logcat:
D/myDebug: onResponse: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 2 column 1 path $
I think there is something wrong with your pojo objects. It should be like this according to your response
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Branch {
#SerializedName("branchName")
#Expose
private String branchName;
#SerializedName("branchPhone")
#Expose
private String branchPhone;
#SerializedName("openingTime")
#Expose
private String openingTime;
#SerializedName("closingTime")
#Expose
private String closingTime;
#SerializedName("branchLat")
#Expose
private String branchLat;
#SerializedName("branchLon")
#Expose
private String branchLon;
#SerializedName("branchAddressNote")
#Expose
private String branchAddressNote;
public String getBranchName() {
return branchName;
}
public void setBranchName(String branchName) {
this.branchName = branchName;
}
public String getBranchPhone() {
return branchPhone;
}
public void setBranchPhone(String branchPhone) {
this.branchPhone = branchPhone;
}
public String getOpeningTime() {
return openingTime;
}
public void setOpeningTime(String openingTime) {
this.openingTime = openingTime;
}
public String getClosingTime() {
return closingTime;
}
public void setClosingTime(String closingTime) {
this.closingTime = closingTime;
}
public String getBranchLat() {
return branchLat;
}
public void setBranchLat(String branchLat) {
this.branchLat = branchLat;
}
public String getBranchLon() {
return branchLon;
}
public void setBranchLon(String branchLon) {
this.branchLon = branchLon;
}
public String getBranchAddressNote() {
return branchAddressNote;
}
public void setBranchAddressNote(String branchAddressNote) {
this.branchAddressNote = branchAddressNote;
}
}
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("shop")
#Expose
private List<Shop> shop = null;
public List<Shop> getShop() {
return shop;
}
public void setShop(List<Shop> shop) {
this.shop = shop;
}
}
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Shop {
#SerializedName("shopName")
#Expose
private String shopName;
#SerializedName("shopID")
#Expose
private String shopID;
#SerializedName("isPaid")
#Expose
private String isPaid;
#SerializedName("branches")
#Expose
private List<Branch> branches = null;
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getShopID() {
return shopID;
}
public void setShopID(String shopID) {
this.shopID = shopID;
}
public String getIsPaid() {
return isPaid;
}
public void setIsPaid(String isPaid) {
this.isPaid = isPaid;
}
public List<Branch> getBranches() {
return branches;
}
public void setBranches(List<Branch> branches) {
this.branches = branches;
}
}

JSON to Java Object get property to compare

After using http://www.jsonschema2pojo.org/ to create POJO class to convert JSON to Java Object I'm trying to get property of "distance" "inMeters" to compare them but I can't get them because it is List is there any way I can compare them
{
"originAddresses": [
"58 Oxford St, Fitzrovia, London W1D 1BH, UK"
],
"destinationAddresses": [
"109 Marylebone High St, Marylebone, London W1U 4RX, UK",
"143 Great Titchfield St, Fitzrovia, London W1W, UK",
"210 Great Portland St, Fitzrovia, London W1W 5BQ, UK",
"43-51 Great Titchfield St, Fitzrovia, London W1W 7PQ, UK"
],
"rows": [
{
"elements": [
{
"status": "OK",
"duration": {
"inSeconds": 457,
"humanReadable": "8 mins"
},
"distance": {
"inMeters": 1662,
"humanReadable": "1.7 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 383,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 1299,
"humanReadable": "1.3 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 376,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 1352,
"humanReadable": "1.4 km"
}
},
{
"status": "OK",
"duration": {
"inSeconds": 366,
"humanReadable": "6 mins"
},
"distance": {
"inMeters": 932,
"humanReadable": "0.9 km"
}
}
]
}
]
}
This is my Main POJO Class in the compareTo class it require int but it show only List :
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class LocationGoogle implements Comparable<LocationGoogle> {
public LocationGoogle(String originAddress, String destinationAddress,Row
rows){
super();
this.destinationAddresses = destinationAddresses;
this.originAddresses = originAddresses;
this.rows= (List<Row>) rows;
}
#SerializedName("originAddresses")
#Expose
private List<String> originAddresses = null;
#SerializedName("destinationAddresses")
#Expose
private List<String> destinationAddresses = null;
#SerializedName("rows")
#Expose
private List<Row> rows = null;
public List<String> getOriginAddresses(){
return originAddresses;
}
public void setOriginAddresses(List<String> originAddresses){
this.originAddresses = originAddresses;
}
public List<String> getDestinationAddresses(){
return destinationAddresses;
}
public void setDestinationAddresses(List<String> destinationAddresses){
this.destinationAddresses = destinationAddresses;
}
public List<Row> getRows(){
return rows;
}
public void setRows(List<Row> rows){
this.rows = rows;
}
#Override
public int compareTo(LocationGoogle compareTime){
int compare =((LocationGoogle)compareTime).getRows();
return 0;
}
}
Is JSON to Java Object is good or bad way to convert JSON to java data. Should I keep doing this or find another way?
This is class Row :
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Row {
#SerializedName("elements")
#Expose
private List<Element> elements = null;
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
#Override
public String toString(){
return String.valueOf(elements);
}
}
This is Elements class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Element {
#SerializedName("status")
#Expose
private String status;
#SerializedName("duration")
#Expose
private Duration duration;
#SerializedName("distance")
#Expose
private Distance distance;
#Override
public String toString(){
return String.valueOf(distance);
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
}
This is Duration class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Duration {
#SerializedName("inSeconds")
#Expose
private Integer inSeconds;
#SerializedName("humanReadable")
#Expose
private String humanReadable;
public Integer getInSeconds() {
return inSeconds;
}
public void setInSeconds(Integer inSeconds) {
this.inSeconds = inSeconds;
}
public String getHumanReadable() {
return humanReadable;
}
public void setHumanReadable(String humanReadable) {
this.humanReadable = humanReadable;
}
#Override
public String toString (){
return String.valueOf(inSeconds);
}
}
This is Distance class:
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Distance implements Comparable{
#SerializedName("inMeters")
#Expose
private Integer inMeters;
#SerializedName("humanReadable")
#Expose
private String humanReadable;
public Integer getInMeters() {
return inMeters;
}
public void setInMeters(Integer inMeters) {
this.inMeters = inMeters;
}
public String getHumanReadable() {
return humanReadable;
}
public void setHumanReadable(String humanReadable) {
this.humanReadable = humanReadable;
}
#Override
public String toString(){
return String.valueOf(inMeters);
}
#Override
public int compareTo(Object o){
int compare = ((Distance)o).getInMeters();
return compare-this.inMeters;
}
}
The code i using to compare them:
#Override
public int compareTo(LocationGoogle compareTime){
String i= getRows()
int compare =((LocationGoogle)compareTime).getRows();
return 0;
}
After seeing required int but have List i confusing.
FileReader reader = new FileReader("Path to json file");
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(reader);
System.out.println("json object = "+json.toString());
JSONArray result = (JSONArray) json.get("rows");
JSONObject result1 = (JSONObject)result.get(0);
JSONArray elements = (JSONArray) result1.get("elements");
JSONObject result2 = (JSONObject)elements.get(0);
JSONObject distance = (JSONObject)result2.get("distance");
JSONObject duration = (JSONObject)result2.get("duration");
Distance=(String)distance.get("inMeters");
use json_simple-1.0.2.jar file. It is step by step extraction.

Reading a json using jackson

I'm having trouble reading this json, the code seems to work, but there's 2 problems
It only reads one block of the json, not entirely.
It always has "null" as a value in the properties.
I've been trying to show the json organized in the console, but when i try those 2 things happens.
Sample of the JSON data:
{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Total [249] records found." ],
"result" : [ {
"name" : "Afghanistan",
"alpha2_code" : "AF",
"alpha3_code" : "AFG"
}, {
"name" : "Ă…land Islands",
"alpha2_code" : "AX",
"alpha3_code" : "ALA"
}, {
"name" : "Albania",
"alpha2_code" : "AL",
"alpha3_code" : "ALB"
}, ...
]
}
}
My code:
public class jsonController {
public void run() {
ObjectMapper mapper = new ObjectMapper();
try {
jsonHandler obj = mapper.readValue(new URL("http://services.groupkt.com/country/get/all"), jsonHandler.class);
//Organized Print
String organizedprint = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(organizedprint);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And in the main i've got
jsonController obj = new jsonController();
obj.run();
And here's the jsonHandler
#JsonIgnoreProperties(ignoreUnknown=true)
public class jsonHandler {
private String restResponse;
private String messages;
private String result;
private String name;
private String alpha2;
private String alpha3;
}
Any idea what I'm doing wrong?
You declared your data types incorrectly in your model. Your Java code declares that the data will have a single object containing 6 string attributes. The JSON data provided by the server is not like that at all. For example, messages is a list of strings and result is a list of objects, not a string. You need to declare your Java model accordingly.
For example:
public class jsonHandler
{
private RestResponseStructure restResponse;
}
public class RestResponseStructure
{
private List<String> messages;
private List<CountryRecord> results;
}
public class CountryRecord {
private String name;
private String alpha2_code;
private String alpha3_code;
}
Okay your mapping class, jsonHandler is wrong. First of all, it should be capitalized correctly (JsonHandler)
Using http://www.jsonschema2pojo.org/ i generated a better model. It's composed of 3 classes. Simply change the package "com.example" to yours.
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"RestResponse"
})
public class JsonHandler {
#JsonProperty("RestResponse")
private RestResponse restResponse;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("RestResponse")
public RestResponse getRestResponse() {
return restResponse;
}
#JsonProperty("RestResponse")
public void setRestResponse(RestResponse restResponse) {
this.restResponse = restResponse;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
com.example.RestResponse.java
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"messages",
"result"
})
public class RestResponse {
#JsonProperty("messages")
private List<String> messages = null;
#JsonProperty("result")
private List<Result> result = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("messages")
public List<String> getMessages() {
return messages;
}
#JsonProperty("messages")
public void setMessages(List<String> messages) {
this.messages = messages;
}
#JsonProperty("result")
public List<Result> getResult() {
return result;
}
#JsonProperty("result")
public void setResult(List<Result> result) {
this.result = result;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
com.example.Result.java
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"name",
"alpha2_code",
"alpha3_code"
})
public class Result {
#JsonProperty("name")
private String name;
#JsonProperty("alpha2_code")
private String alpha2Code;
#JsonProperty("alpha3_code")
private String alpha3Code;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("alpha2_code")
public String getAlpha2Code() {
return alpha2Code;
}
#JsonProperty("alpha2_code")
public void setAlpha2Code(String alpha2Code) {
this.alpha2Code = alpha2Code;
}
#JsonProperty("alpha3_code")
public String getAlpha3Code() {
return alpha3Code;
}
#JsonProperty("alpha3_code")
public void setAlpha3Code(String alpha3Code) {
this.alpha3Code = alpha3Code;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

Deserializing list with GSON

I have the following JSON object and I want to deserialize it using Google's GSON library. Unfortunately I am unable to get the list correctly. GSON finds the first list entry but not the second.
This is the code I use for invoking GSON:
Mentions result = gson.fromJson(response, Mentions.class);
Here is my JSON File:
{
"mentions": [
{
"allEntities": [
{
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
],
"name": "Dylan",
"bestEntity": {
"kbIdentifier": "YAGO:Bob_Dylan",
"disambiguationScore": "0.63692"
}
},
{
"name": "Duluth",
"bestEntity": {
"kbIdentifier": "YAGO:Duluth\\u002c_Minnesota",
"disambiguationScore": "0.63149"
}
}
]
}
And these are the plain old java objects I have created:
public class Mentions {
public List<Mention> mentions = new ArrayList<>();
}
public class Mention {
#SerializedName("bestEntity")
public BestEntity entity;
#SerializedName("name")
public String name;
}
public class BestEntity {
#SerializedName("kbIdentifier")
public String kbIdentifier;
#SerializedName("disambiguationScore")
public Double disambiguationScore;
}
I also tried directly deserializing the list, but it just gives me an error, saying that GSON expects the list to start at the beginning of the input.
Type datasetListType = new TypeToken<Collection<Mention>>() {
}.getType();
List<Mention> mentions = gson.fromJson(response, datasetListType);
Try this -
AllEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AllEntity {
#SerializedName("kbIdentifier")
#Expose
private String kbIdentifier;
#SerializedName("disambiguationScore")
#Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
#Override
public String toString() {
return "AllEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
BestEntity.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BestEntity {
#SerializedName("kbIdentifier")
#Expose
private String kbIdentifier;
#SerializedName("disambiguationScore")
#Expose
private String disambiguationScore;
public String getKbIdentifier() {
return kbIdentifier;
}
public void setKbIdentifier(String kbIdentifier) {
this.kbIdentifier = kbIdentifier;
}
public String getDisambiguationScore() {
return disambiguationScore;
}
public void setDisambiguationScore(String disambiguationScore) {
this.disambiguationScore = disambiguationScore;
}
#Override
public String toString() {
return "BestEntity [kbIdentifier=" + kbIdentifier
+ ", disambiguationScore=" + disambiguationScore + "]";
}
}
Mention.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Mention {
#SerializedName("allEntities")
#Expose
private List<AllEntity> allEntities = new ArrayList<AllEntity>();
#SerializedName("name")
#Expose
private String name;
#SerializedName("bestEntity")
#Expose
private BestEntity bestEntity;
public List<AllEntity> getAllEntities() {
return allEntities;
}
public void setAllEntities(List<AllEntity> allEntities) {
this.allEntities = allEntities;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BestEntity getBestEntity() {
return bestEntity;
}
public void setBestEntity(BestEntity bestEntity) {
this.bestEntity = bestEntity;
}
#Override
public String toString() {
return "Mention [allEntities=" + allEntities + ", name=" + name
+ ", bestEntity=" + bestEntity + "]";
}
}
Main.java
import com.example.ElemntList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
/**
* #param args
*/
public static void main(String[] args) {
String s = "{\"mentions\":[{\"allEntities\":[{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}],\"name\":\"Dylan\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Bob_Dylan\",\"disambiguationScore\":\"0.63692\"}},{\"name\":\"Duluth\",\"bestEntity\":{\"kbIdentifier\":\"YAGO:Duluth\\u002c_Minnesota\",\"disambiguationScore\":\"0.63149\"}}]}";
ElemntList info = gson.fromJson(s, ElemntList.class);
System.out.println(info);
}
}
Result is -
ElemntList [mentions=[Mention [allEntities=[AllEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], name=Dylan, bestEntity=BestEntity [kbIdentifier=YAGO:Bob_Dylan, disambiguationScore=0.63692]], Mention [allEntities=[], name=Duluth, bestEntity=BestEntity [kbIdentifier=YAGO:Duluth,_Minnesota, disambiguationScore=0.63149]]]]
Shouldn't you use the class you've created ? I.E Mentions
gson.fromJson(response, Mentions.class);
And if I were you, I would map all fields just in case you may need it, you're missing allEntities.

Categories