I've been racking my brain attempting to make pojos to consume the following json string. One thing I've been doing is making multiple pojos within pojos similar to what would be necessary inside of spring boot. Not sure if this is also needed for GSON. After numerous attempts I've still havent gotten it. Thanks for any advice in advance.
Json String:
"results": [
{
"id": "superficial",
"language": "en",
"lexicalEntries": [
{
"derivatives": [
{
"id": "superficialness",
"text": "superficialness"
}
],
"entries": [
{
"etymologies": [
"late Middle English: from late Latin superficialis, from Latin superficies (see superficies)"
],
"grammaticalFeatures": [
{
"text": "Positive",
"type": "Degree"
}
],
"homographNumber": "000",
"senses": [
{
"definitions": [
"existing or occurring at or on the surface"
],
"examples": [
{
"text": "the building suffered only superficial damage"
}
],
"id": "m_en_gbus1014360.017",
"short_definitions": [
"existing or occurring at or on surface"
],
"subsenses": [
{
"definitions": [
"situated or occurring on the skin or immediately beneath it"
],
"domains": [
"Anatomy",
"Medicine"
],
"examples": [
{
"text": "the superficial muscle groups"
}
],
"id": "m_en_gbus1014360.019",
"short_definitions": [
"situated or occurring on skin or immediately beneath it"
]
},
{
"definitions": [
"appearing to be true or real only until examined more closely"
],
"examples": [
{
"text": "the resemblance between the breeds is superficial"
}
],
"id": "m_en_gbus1014360.020",
"short_definitions": [
"appearing to be true or real only until examined more closely"
],
"thesaurusLinks": [
{
"entry_id": "superficial",
"sense_id": "t_en_gb0014419.004"
}
]
},
{
"definitions": [
"not thorough, deep, or complete; cursory"
],
"examples": [
{
"text": "he had only the most superficial knowledge of foreign countries"
}
],
"id": "m_en_gbus1014360.021",
"short_definitions": [
"not thorough or complete"
],
"thesaurusLinks": [
{
"entry_id": "superficial",
"sense_id": "t_en_gb0014419.003"
}
]
},
{
"definitions": [
"not having or showing any depth of character or understanding"
],
"examples": [
{
"text": "perhaps I was a superficial person"
}
],
"id": "m_en_gbus1014360.022",
"short_definitions": [
"not having or showing any depth of character or understanding"
],
"thesaurusLinks": [
{
"entry_id": "superficial",
"sense_id": "t_en_gb0014419.006"
},
{
"entry_id": "superficial",
"sense_id": "t_en_gb0014419.002"
}
]
}
],
"thesaurusLinks": [
{
"entry_id": "superficial",
"sense_id": "t_en_gb0014419.001"
}
]
}
]
}
],
"language": "en",
"lexicalCategory": "Adjective",
"pronunciations": [
{
"dialects": [
"American English"
],
"phoneticNotation": "respell",
"phoneticSpelling": "ˌso͞opərˈfiSHəl"
},
{
"audioFile": "http://audio.oxforddictionaries.com/en/mp3/superficial_us_1.mp3",
"dialects": [
"American English"
],
"phoneticNotation": "IPA",
"phoneticSpelling": "ˌsupərˈfɪʃəl"
}
],
"text": "superficial"
}
],
"type": "headword",
"word": "superficial"
}
Pojos:
class Results {
private String id;
private String language;
private String lexicalEntries;
private String type;
private String word;
//
}
class Derivatives {
private String id;
private String text;
//
}
class Entries {
private String etymologies;
private String grammaticalFeatures;
private int homographNumber;
private List<String> senses;
//
}
public class LexicalEntries {
private Derivatives derivatives;
private List<Entries> entries;
private String language;
private String lexicalCategory;
private List<Pronunciations> pronunciations;
private String text;
//
}
public class Pronunciations {
private String dialects;
private String phoneticNotation;
private String phoneticSpelling;
//
}
class Senses {
private String definitions;
private String examples;
private String id;
private ShortDefinitions short_definitions;
private List<Subsenses> subsenses;
private List<ThesaurusLinks> thesaurusLinks;
//
}
class ShortDefinitions {
private String short_definitions;
//
}
class Subsenses {
private String definitions;
private String domains;
private String examples;
private String id;
private String shortDefinitions;
private String thesaurusLinks;
//
}
class ThesaurusLinks {
private String entry_id;
private String sense_id;
//
}
I have corrected your POJO class definitions as per your JSON.
I would recommend you reading JSON notation, how different data types are represented in it like Array/List, Object, String, int, boolean. It will clarify your understanding and you will know why your classes were not properly mapped to JSON data schema.
class Results {
private String id;
private String language;
private List<LexicalEntry> lexicalEntries;
private String type;
private String word;
//
}
public class LexicalEntry {
private List<Derivative> derivatives;
private List<Entry> entries;
private String language;
private String lexicalCategory;
private List<Pronunciation> pronunciations;
private String text;
//
}
class Derivative {
private String id;
private String text;
//
}
class Entry {
private List<String> etymologies;
private List<GrammaticalFeature> grammaticalFeatures;
private String homographNumber; //if it has quotes in JSON, it will be a string not int..JSON is a strongly typed object notation
private List<Sense> senses;
//
}
class GrammaticalFeature{
String text;
String type;
}
public class Pronunciation {
private String audioFile;
private List<String> dialects;
private String phoneticNotation;
private String phoneticSpelling;
//
}
class Sense {
private List<String> definitions;
private List<Example> examples;
private String id;
private List<String> short_definitions;
private List<Subsense> subsenses;
private List<ThesaurusLinks> thesaurusLinks;
//
}
class Example{
String text;
}
class Subsense {
private List<String> definitions;
private List<String> domains;
private List<Example> examples;
private String id;
private List<String> shortDefinitions;
private List<ThesaurusLink> thesaurusLinks;
//
}
class ThesaurusLink {
private String entry_id;
private String sense_id;
//
}
Related
I'm having problems parsing JSON, this is the error:
out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList<packagename....>` out of START_OBJECT token
And I know why it is happening I just don't know how to fix it. This JSON works:
{
"status_code": "SUCCESS",
"time": {
"date": "Mar 23, 2021 1:14:39 AM"
},
"info": [
{
"person": "2.2",
"role": "TEACHER"
},
{
"person": "2.3",
"role": "TEACHER"
}
]
}
This one does not:
{
"status_code": "SUCCESS",
"time": {
"date": "Mar 23, 2021 3:49:27 AM"
},
"info": {
"id": "1",
"person": [
{
"identifier": "John",
"role": "TEACHER"
},
{
"identifier": "Homer",
"role": "TEACHER"
},
{
"identifier": "Michael",
"role": "TEACHER"
},
{
"identifier": "Sarah",
"role": "TEACHER"
}
]
}
}
The problem seems to be the { character in front of the info field because with [ works. So this is the method I'm using to parse the JSON:
public Mono<PersonResponse> searchById(String id) {
return webClient.get().uri(id).retrieve().bodyToMono(PersonResponse.class);
}
Also tried:
public Mono<PersonResponse[]> searchById(String id) {
return webClient.get().uri(id).retrieve().bodyToMono(PersonResponse[].class);
}
Error right on line: 1, column: 1. Any suggestions of how to implement the method?
EDIT: Added classes.
PersonResponse:
public class PersonResponse implements Serializable{
private static final long serialVersionUID = 7506229887182440471L;
public String status_code;
public Timestamp time;
public List<PersonDetails> info;
public PersonResponse() {}
...getters / setters / toSting
PersonDetails:
public class PersonDetails implements Serializable{
private static final long serialVersionUID = 1294417456651475410L;
private int id;
private List<Person> person;
public PersonDetails(int version) {
super();
this.version = version;
}
...getters / setters / toSting
Person
public class Person implements Serializable{
private static final long serialVersionUID = 3290753964441709903L;
private String identifier;
private String role;
public Person(String identifier, String role) {
super();
this.identifier = identifier;
this.role = role;
}
...getters / setters / toSting
The problem isn't the JSON necessarily, it's that the JSON structure doesn't match your PersonResponse class. There's an info variable in PersonResponse that requires an array of what I assume to be persons, in the second example you're trying to push an object in there, which you can't. You have to either change your JSON, which you don't seem to want in this case, or the class you're trying to parse it to.
You need to restructure the info variable in PersonResponse to match the object you're trying to parse to it.
I need to set json in a format provided below.
"Tyre": {
"title": "Tyre",
"cls": "TyreCondition",
"items": [
{
"firstItem": [
{
"title": "Front right tyre",
"value": "50%",
"subValue": "30,000 km Approx"
}
],
"secItem": [
{
"title": "title",
"value": "Front right tyre tread - 50%"
},
{
"title": "title",
"value": "Front right tyre tread - 50%"
}
]
}
]
}
class that i have created for this is looks like:
private String title;
private String cls;
#SerializedName("firstItem")
private List<UsedCarInspectionInfo> items;
#SerializedName("secItem")
private List<UsedCarTyreImage> imageList;
//getter and setter
when i run this code with this class structure, I am getting the json like-
"Tyre": {
"title": "Tyre",
"cls": "TyreCondition",
"firstItem": [
{
"title": "Front right tyre",
"value": "50%",
"subValue": "30,000 km Approx"
}
],
"secItem": [
{
"title": "title",
"value": "Front right tyre tread - 50%"
},
{
"title": "title",
"value": "Front right tyre tread - 50%"
}
]}
Any idea how i can get the firstItem and secItem array in Items array?
You get no items key in your JSON, because you override the items field in your Java class with #SerializedName.
You need something like this:
String title;
String cls;
List<Item> items;
static class Item {
List<FirstItem> firstItem;
List<SecItem> secItem;
}
static class FirstItem {
String title;
String value;
String subValue;
}
static class SecItem {
String title;
String value;
}
So I have a JSON string of countries like this:
{
"details": [
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
}
Now I want to have a method that tries to convert this into an ArrayList of countries.
public static ArrayList<GFSCountry> get() {
return new Gson().fromJson(countriesJson, new TypeToken<ArrayList<GFSCountry>>(){}.getType());
}
But I get an
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path
As per request, here is my GFSCountry class:
#SerializedName("country_id")
#Expose
private String countryId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("regions")
#Expose
private Object regions;
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getRegions() {
return regions;
}
public void setRegions(Object regions) {
this.regions = regions;
}
I know I should adjust something either from the JSON string or the method. Any help?
Since the list is nested in your JSON you will need a small mapping class that contains the list.
Try
static class GFSCountryList {
public List<GFSCountry> details;
}
public static List<GFSCountry> get() {
return new Gson().fromJson(countriesJson, GFSCountryList.class).details;
}
It seems to me that Gson is expecting your json to be like this
[
{
"country_id": "1",
"name": "Afghanistan",
"regions": null
},
{
"country_id": "2",
"name": "Albania",
"regions": null
},
{
"country_id": "3",
"name": "Algeria",
"regions": null
},
... and so on
]
But it encounters an object (marked by { })
Either you have the possibility to change your json format, or you create a class with a "details" attribut as a list to be compatible with the json's format.
I have json response in the form
{
"total": 782,
"category": {
"id": 1120,
"name": "Computers & Programming"
},
"experts": [
{
"id": 385816,
"name": "Master Z",
"title": "Mr",
"description": " Expert in C++",
"profile": "http://...com/experts.svc/1.0/385816/..../json?.."
}
}
]
}
I am able to parse everything else in the experts[] array except "profile" whose value "http://...com/experts.svc/1.0/385816/..../json?.." has the following json response
{
"id": 385816,
"name": "Master Z",
"title": "",
"reviewsCount": 15359,
"averageRating": 4.87,
"status": 4,
"fee": 19.99,
"languages": "English",
"category": {
"id": 1120,
"name": "Computers & Programming"
}
}
The models used are as follows
1. main pojo:
public class ExpertObj
{
private String total;
private Category category;
private Experts[] experts;
}
Category pojo:
public class Category
{
private String id;
private String name;
}
3.Experts array pojo:
public class Experts
{
private String id;
private String name;
private String title;
private String description;
private String profile;
}
Am using Retrift 2.
private RestManager mManager;
List<Expert> mExperts = new ArrayList<>();
....
Call<ExpertsObj> call = mManager.getExpertsService().listAllExperts();
call.enqueue(new Callback<ExpertsObj>() {
#Override
public void onResponse(Call<ExpertsObj> call, Response<ExpertsObj> response) {
if (response.isSuccess()) {
ExpertsObj expertsObj = response.body();
mExperts = expertsObj.getExperts();
....}
At a loss how to parse the profile-url name-value pair and display the results in a detail layout in android.
Any help is appreciated.
New in android. Please excuse if anything is not explained properly.
I am trying to use Gson to extract a field from a Json:
{ "attributes": { "538": { "id": "538", "code": "sabor", "label": "Sabor", "options": [ { "id": "24", "label": "Baunilha", "price": "0", "oldPrice": "0", "products": [ "1376" ] }, { "id": "25", "label": "Chocolate", "price": "0", "oldPrice": "0", "products": [ "1377" ] } ] } } }
What i need is the label field inside the options( in this case, Baunilha and Chocolate).
I tried with the following classes:
public class Customer implements Serializable{
#SerializedName("options")
private Produto options;
public Produto getOptions() {
return options;
}
public void setEmail(Produto options) {
this.options = options;
}
and
public class Produto implements Serializable{
#SerializedName("label")
private String label;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
Customer cust = g.fromJson(ja, Customer.class);
But i keep getting null pointer errors.
the "options" value is not an object consisting of a string, the "options" value is an array of objects. You need to change your definition in Customer to be:
class CustomerWrapper {
#SerializedName("attributes")
private Map<String, Customer> attributes;
}
class Customer {
#SerializedName("options")
private List<Produto> options;
}