I'm new to mongodb and struggle a bit. I want to store a class which contains a HashMap which contains other objects. When I store the object it works without any error and the document in the database looks good. But retrieving the document results in an error:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
My (simplified) classes look like this:
#Entity(value = "abbyy_parameters", noClassnameStored = true)
public class AbbyyParameters extends AbstractModifiableMongoBean {
private String wordListEncoding = DEFAULT_ENCODING;
private String description;
private String name;
private PredefinedProfile predefinedProfile;
#Embedded
private CustomProfile customProfile;
private Parameters wordListActionParameters;
private Boolean treatBarcodeAsWord;
private Boolean documentProcessingEnabled;
private Boolean documentExportEnabled;
private Integer ocrPageLimit;
private Boolean highCommaFixEnabled;
private Double skewAngle;
private List<RegexBasedLanguage> regexBasedLanguages = new ArrayList<>(2);
public AbbyyParameters() {
this.createNewId();
this.setPredefinedProfile(new PredefinedProfile(PredefinedProfileType.DEFAULT));
this.setCustomProfile(new CustomProfile());
}
public String getWordListEncoding() {
return wordListEncoding;
}
public void setWordListEncoding(String encoding) {
if (!TangroUtils.isNullOrBlankString(encoding)) {
this.wordListEncoding = encoding;
}
}
public PredefinedProfile getPredefinedProfile() {
return predefinedProfile;
}
public void setPredefinedProfile(PredefinedProfile profile) {
if (profile == null) {
profile = new PredefinedProfile("Default");
}
this.predefinedProfile = profile;
}
public CustomProfile getCustomProfile() {
return customProfile;
}
public void setCustomProfile(CustomProfile profile) {
this.customProfile = profile;
}
public Optional<Boolean> isBarcodeTreatedAsWord() {
return Optional.ofNullable(treatBarcodeAsWord);
}
public void treatBarcodeAsWord(Boolean treatBarcodeAsWord) {
this.treatBarcodeAsWord = treatBarcodeAsWord;
}
public Optional<Boolean> isDocumentProcessingEnabled() {
return Optional.ofNullable(documentProcessingEnabled);
}
public void enableDocumentProcessing(Boolean enableDocumentProcessing) {
this.documentProcessingEnabled = enableDocumentProcessing;
}
public Optional<Boolean> isDocumentExportEnabled() {
return Optional.ofNullable(documentExportEnabled);
}
public void enableDocumentExport(Boolean exportDocument) {
this.documentExportEnabled = exportDocument;
}
public Optional<String> getDescription() {
return Optional.ofNullable(description);
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#Entity
public class CustomProfile {
private static final String DEFAULT_FILE_NAME = "custom";
#Transient
private String name;
#Embedded
private Map<String, ProfileProperties> properties = new HashMap<>(5);
public CustomProfile() {
}
public String getName() {
return name;
}
private void setName (String name) {
this.name = name;
}
public Map<String, ProfileProperties> getProperties() {
return properties;
}
private void setProperties(Map<String, ProfileProperties> properties) {
this.properties = properties;
}
}
#Embedded
public class ProfileProperties implements Iterable<ProfileProperty>, Serializable {
private static final long serialVersionUID = 1L;
#Embedded
private List<ProfileProperty> properties = new ArrayList<>(15);
public List<ProfileProperty> getProperties() {
return properties;
}
public void setProperties(List<ProfileProperty> properties) {
this.properties = properties;
}
public void add(ProfileProperty property) {
Optional<ProfileProperty> oldPropertyOpt = get(property.getName());
if (oldPropertyOpt.isPresent()) {
ProfileProperty oldProperty = oldPropertyOpt.get();
oldProperty.setValue(property.getValue());
} else {
properties.add(property);
}
}
public Optional<ProfileProperty> get(String propertyName) {
if (propertyName == null) {
return Optional.empty();
}
for(ProfileProperty property : properties) {
if (propertyName.equals(property.getName())) {
return Optional.of(property);
}
}
return Optional.empty();
}
#Override
public Iterator<ProfileProperty> iterator() {
return properties.iterator();
}
}
#Embedded
public class ProfileProperty implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String value;
public ProfileProperty(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
I created morphia and told it how to map:
morphia = new Morphia();
morphia.map(AbbyyParameters.class,
CustomProfile.class,
ProfileProperties.class,
ProfileProperty.class);
After storing the class in the database the document look like this:
{
"_id" : ObjectId("5b2906a0cac45b8d42bbda91"),
"wordListEncoding" : "ISO-8859-15",
"description" : "",
"name" : "1",
"predefinedProfile" : {
"type" : "DEFAULT"
},
"customProfile" : {
"properties" : {
"PageAnalysisParams" : {
"properties" : [
{
"name" : "DetectBarcodes",
"value" : "true"
}
]
},
"RecognizerParams" : {
"properties" : [
{
"name" : "TextLanguage",
"value" : "English,German,Digits,French,Italian,Spanish,Croatian,Slovak,Bulgarian"
}
]
}
}
},
"treatBarcodeAsWord" : false,
"documentExportEnabled" : false,
"creationDate" : ISODate("2018-06-19T13:35:26.019Z"),
"changedDate" : ISODate("2018-06-19T13:35:28.441Z")
}
When I try to retrieve the document I get the following error:
Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.mongodb.morphia.mapping.EmbeddedMapper.readMap(EmbeddedMapper.java:166)
I stepped into the code so I found that this code raises the exception:
new EphemeralMappedField((ParameterizedType) mf.getSubType(), mf, mapper);
mf.getSubType() returns ProfileProperties so I guess I have misconfigured something there?
What do I have to do that I can retrieve my document?
Related
This json occurs when a destination or origin is outside of the uk, therefore not giving me any results! I need to check for this for a null check so i dont receive null pointer exception
JSON RESULT:
{
"destination_addresses" : [ "Durham, NC, USA" ],
"origin_addresses" : [ "Lancashire, UK" ],
"rows" : [
{
"elements" : [
{
"status" : "ZERO_RESULTS"
}
]
}
],
"status" : "OK"
}
Code:
public static void extractJsonFromRequest(GoogleResponsePojo response) {
String destinationAddress =
response.getDestination_addresses().get(0);
String timeTaken =
response.getRows().get(0).getElements().get(0).getDuration().getText();
String originAddress = response.getOrigin_addresses().get(0);
System.out.println("It will take ** "+ timeTaken + " ** to walk
from " + originAddress + " to " + destinationAddress);
}
Google Reponse POJO which is structure of json:
public class GoogleResponsePojo {
private List<String> destination_addresses;
private List<String> origin_addresses;
private List<Rows> rows;
public List<String> getDestination_addresses() {
return destination_addresses;
}
public void setDestination_addresses(List<String> destination_addresses) {
this.destination_addresses = destination_addresses;
}
public List<String> getOrigin_addresses() {
return origin_addresses;
}
public void setOrigin_addresses(List<String> origin_addresses) {
this.origin_addresses = origin_addresses;
}
public List<Rows> getRows() {
return rows;
}
public void setRows(List<Rows> rows) {
this.rows = rows;
}
}
class Rows {
private List<Element> elements;
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
class Element {
private TextValue distance;
private TextValue duration;
public TextValue getDistance() {
return distance;
}
public void setDistance(TextValue distance) {
this.distance = distance;
}
public TextValue getDuration() {
return duration;
}
public void setDuration(TextValue duration) {
this.duration = duration;
}
}
class TextValue {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
I essentially need to just parse the json below so that i can say (if status != ZERO_RESULTS ) save the response else throw an exception! Probably easy but im struggling! Thanks so much!
Change GoogleResponsePojo to:
public class GoogleResponsePojo {
private List<String> destination_addresses;
private List<String> origin_addresses;
private List<Rows> rows;
public void setDestination_addresses(List<String> destination_addresses) {
this.destination_addresses = destination_addresses;
}
public void setOrigin_addresses(List<String> origin_addresses) {
this.origin_addresses = origin_addresses;
}
public void setRows(List<Rows> rows) {
this.rows = rows;
}
//getters
}
private static class Rows{
private List<Element> elements;
public void setElements(List<Element> elements) {
this.elements = elements;
}
//getters
}
private static class Element{
private TextValue distance;
private TextValue duration;
public void setDistance(TextValue distance) {
this.distance = distance;
}
public void setDuration(TextValue duration) {
this.duration = duration;
}
//getters
}
private static class TextValue{
private String text;
private String value;
public void setText(String text) {
this.text = text;
}
public void setValue(String value) {
this.value = value;
}
//getters
}
You can take duration as following:
GoogleResponsePojo name = gson.fromJson(response.toString(),GoogleResponsePojo.class);
name.getRows().get(0).getDuration().getText();
And I recommend use http-request built on apache http api. Its simple to use:
public static final String BASE_URL = "https://maps.googleapis.com/maps/api/distancematrix/json";
private static final HttpRequest<GoogleResponsePojo> HTTP_REQUEST =
HttpRequestBuilder.createGet(BASE_URL, GoogleResponsePojo.class)
.addDefaultRequestParameter("origins", "Seattle")
.addDefaultRequestParameter("destinations", "San+Francisco")
.addDefaultRequestParameter("key", "***")
.build();
#GET
#Produces(MediaType.APPLICATION_JSON)
public static void updateTestExecutionDetails() throws IOException {
ResponseHandler<GoogleResponsePojo> responseHandler = HTTP_REQUEST.execute();
GoogleResponsePojo name = responseHandler.orElseThrow(); // throws ResponseException when status code != 200
System.out.println(name.getDestination_addresses().get(0));
System.out.println(name.getRows().get(0).getElements().get(0).getDuration().getText());
System.out.println(name.getOrigin_addresses().get(0));
}
In JSON Response there is key "Value" but its response have multiple forms like String and Array with same key "Value".
So how to make Retrofit model class to maintain String and Array with same key "Value".
{
"RespCode":"SUCCESS",
"RespText":"Transaction Details",
"Data":{
"Record":[
{
"group_title":"Seller Information",
"group_values":[
{
"key":"Listing Agent",
"value":[
{
"key":"Agent First Name",
"value":"Myks"
},
{
"key":"Agent Last Name",
"value":"Joe"
},
{
"key":"Company",
"value":"bdfjdlfdf"
},
{
"key":"Phone",
"value":"712.336.4967"
},
{
"key":"Email",
"value":"abc#gmail.com"
}
]
},
{
"key":"Cell Phone",
"value":"012.345.6789"
},
{
"key":"Email",
"value":"balt#gmail.com.com"
},
{
"key":"Preferred Contact Method",
"value":"Phone"
}
]
},
]
}
}
Just use an arraylist that contains multiple hashmaps maybe? Or... You have to define a pojo that has list of arrays with type map or something to that effect
Check this:
public class ModelBean {
private String RespCode;
private String RespText;
private DataBean Data;
public String getRespCode() {
return RespCode;
}
public void setRespCode(String RespCode) {
this.RespCode = RespCode;
}
public String getRespText() {
return RespText;
}
public void setRespText(String RespText) {
this.RespText = RespText;
}
public DataBean getData() {
return Data;
}
public void setData(DataBean Data) {
this.Data = Data;
}
public static class DataBean {
private List<RecordBean> Record;
public List<RecordBean> getRecord() {
return Record;
}
public void setRecord(List<RecordBean> Record) {
this.Record = Record;
}
public static class RecordBean {
private String group_title;
private List<GroupValuesBean> group_values;
public String getGroup_title() {
return group_title;
}
public void setGroup_title(String group_title) {
this.group_title = group_title;
}
public List<GroupValuesBean> getGroup_values() {
return group_values;
}
public void setGroup_values(List<GroupValuesBean> group_values) {
this.group_values = group_values;
}
public static class GroupValuesBean {
private String key;
private List<ValueBean> value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<ValueBean> getValue() {
return value;
}
public void setValue(List<ValueBean> value) {
this.value = value;
}
public static class ValueBean {
private String key;
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
}
}
}
I am trying to get java object from dynamic JSON.
One Important point these given classes are from third party API.
#JsonTypeInfo(
use = Id.NAME,
include = As.PROPERTY,
property = "nodeType"
)
#JsonSubTypes({ #Type(
name = "Filter",
value = Filter.class
), #Type(
name = "Criterion",
value = Criterion.class
)})
public abstract class Node {
public Node() {
}
#JsonIgnore
public EvaluationResult evaluate(Map<UUID, List<AnswerValue>> answers) {
Evaluator evaluator = new Evaluator();
return evaluator.evaluateAdvancedLogic(this, answers);
}
}
Filter.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"evaluationType", "filters"})
public class Filter extends Node {
#JsonProperty("evaluationType")
private EvaluationType evaluationType;
#NotNull
#JsonProperty("filters")
#Valid
private List<Node> filters = new ArrayList();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Filter() {
}
#JsonProperty("evaluationType")
public EvaluationType getEvaluationType() {
return this.evaluationType;
}
#JsonProperty("evaluationType")
public void setEvaluationType(EvaluationType evaluationType) {
this.evaluationType = evaluationType;
}
#JsonProperty("filters")
public List<Node> getFilters() {
return this.filters;
}
#JsonProperty("filters")
public void setFilters(List<Node> filters) {
this.filters = filters;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
}
Criterion.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"fieldSourceType", "fieldCategoryName", "sequenceNumber", "fieldName", "values", "operator", "fieldId"})
public class Criterion extends Node {
#JsonProperty("fieldSourceType")
private FieldSourceType fieldSourceType;
#JsonProperty("fieldCategoryName")
private String fieldCategoryName;
#NotNull
#JsonProperty("sequenceNumber")
private Long sequenceNumber;
#JsonProperty("fieldName")
private String fieldName;
#JsonProperty("values")
#Valid
private List<String> values = new ArrayList();
#JsonProperty("operator")
#Valid
private Operator operator;
#NotNull
#JsonProperty("fieldId")
private UUID fieldId;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Criterion() {
}
#JsonProperty("fieldSourceType")
public FieldSourceType getFieldSourceType() {
return this.fieldSourceType;
}
#JsonProperty("fieldSourceType")
public void setFieldSourceType(FieldSourceType fieldSourceType) {
this.fieldSourceType = fieldSourceType;
}
#JsonProperty("fieldCategoryName")
public String getFieldCategoryName() {
return this.fieldCategoryName;
}
#JsonProperty("fieldCategoryName")
public void setFieldCategoryName(String fieldCategoryName) {
this.fieldCategoryName = fieldCategoryName;
}
#JsonProperty("sequenceNumber")
public Long getSequenceNumber() {
return this.sequenceNumber;
}
#JsonProperty("sequenceNumber")
public void setSequenceNumber(Long sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
#JsonProperty("fieldName")
public String getFieldName() {
return this.fieldName;
}
#JsonProperty("fieldName")
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
#JsonProperty("values")
public List<String> getValues() {
return this.values;
}
#JsonProperty("values")
public void setValues(List<String> values) {
this.values = values;
}
#JsonProperty("operator")
public Operator getOperator() {
return this.operator;
}
#JsonProperty("operator")
public void setOperator(Operator operator) {
this.operator = operator;
}
#JsonProperty("fieldId")
public UUID getFieldId() {
return this.fieldId;
}
#JsonProperty("fieldId")
public void setFieldId(UUID fieldId) {
this.fieldId = fieldId;
}
}
The json used to conversion is this.
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
{
"fieldName":"sdada",
"values":"sdad",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dasa",
"values":"das",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dada",
"values":"dads",
"operator":{
"operatorType":"Equals"
}
}
]
}
The problem is that deserialization of this JSON fails with following error:
{
"message": "Class com.cvent.logic.model.Criterion is not assignable to com.cvent.logic.model.Filter"
}
The first part of the JSON is wrong
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
It says that the type is Criterion but it has evaluationType from Filter.
Also, probably "Criterion" : [ should be "filters" : [
This is the structure of the JSON I need to Load,
{
"readme_0" : "THIS JSON IS THE RESULT OF YOUR SEARCH QUERY - THERE IS NO WEB PAGE WHICH SHOWS THE RESULT!",
"readme_1" : "loklak.org is the framework for a message search system, not the portal, read: http://loklak.org/about.html#notasearchportal",
"readme_2" : "This is supposed to be the back-end of a search portal. For the api, see http://loklak.org/api.html",
"readme_3" : "Parameters q=(query), source=(cache|backend|twitter|all), callback=p for jsonp, maximumRecords=(message count), minified=(true|false)",
"search_metadata" : {
"itemsPerPage" : "100",
"count" : "100",
"count_twitter_all" : 0,
"count_twitter_new" : 100,
"count_backend" : 0,
"count_cache" : 78780,
"hits" : 78780,
"period" : 3066,
"query" : "apple",
"client" : "180.215.121.78",
"time" : 5219,
"servicereduction" : "false",
"scraperInfo" : "http://45.55.245.191:9000,local"
},
"statuses" : [ {
"created_at" : "2016-01-09T12:11:38.000Z",
"screen_name" : "arifazmi92",
"text" : "Perhaps I shouldn't have eaten that pisang goreng cheese perisa green apple. <img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\"><img class=\"Emoji Emoji--forText\" src=\"https://abs.twimg.com/emoji/v2/72x72/1f605.png\" draggable=\"false\" alt=\"😅\" title=\"Smiling face with open mouth and cold sweat\" aria-label=\"Emoji: Smiling face with open mouth and cold sweat\">",
"link" : "https://twitter.com/arifazmi92/status/685796067082813440",
"id_str" : "685796067082813440",
"source_type" : "TWITTER",
"provider_type" : "SCRAPED",
"retweet_count" : 0,
"favourites_count" : 0,
"images" : [ ],
"images_count" : 0,
"audio" : [ ],
"audio_count" : 0,
"videos" : [ ],
"videos_count" : 0,
"place_name" : "Bandar Shah Alam, Selangor",
"place_id" : "9be3b0eca6c21f6c",
"place_context" : "FROM",
"place_country" : "Malaysia",
"place_country_code" : "MY",
"place_country_center" : [ -59.30559537806809, 3.4418498787292435 ],
"location_point" : [ 101.53280621465888, 3.0850698533863863 ],
"location_radius" : 0,
"location_mark" : [ 101.52542227271437, 3.0911033774188725 ],
"location_source" : "PLACE",
"hosts" : [ "abs.twimg.com" ],
"hosts_count" : 1,
"links" : [ "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"", "https://abs.twimg.com/emoji/v2/72x72/1f605.png\"" ],
"links_count" : 3,
"mentions" : [ ],
"mentions_count" : 0,
"hashtags" : [ ],
"hashtags_count" : 0,
"without_l_len" : 626,
"without_lu_len" : 626,
"without_luh_len" : 626,
"user" : {
"screen_name" : "arifazmi92",
"user_id" : "44503967",
"name" : "Arif Azmi",
"profile_image_url_https" : "https://pbs.twimg.com/profile_images/685788990004301824/NbFnnLuO_bigger.jpg",
"appearance_first" : "2016-01-09T12:11:57.933Z",
"appearance_latest" : "2016-01-09T12:11:57.933Z"
}
}
} ],
"aggregations" : { }
}
And these are my POJO classes that I've generated:
MainPojo.class
public class MainPojo
{
#SerializedName("readme_0")
#Expose
private String readme0;
#SerializedName("readme_1")
#Expose
private String readme1;
#SerializedName("readme_2")
#Expose
private String readme2;
#SerializedName("readme_3")
#Expose
private String readme3;
#SerializedName("search_metadata")
#Expose
private SearchMetadata searchMetadata;
#SerializedName("statuses")
#Expose
private List<Status> statuses = new ArrayList<Status>();
#SerializedName("aggregations")
#Expose
private Aggregations aggregations;
public String getReadme0() {
return readme0;
}
public void setReadme0(String readme0) {
this.readme0 = readme0;
}
public String getReadme1() {
return readme1;
}
public void setReadme1(String readme1) {
this.readme1 = readme1;
}
public String getReadme2() {
return readme2;
}
public void setReadme2(String readme2) {
this.readme2 = readme2;
}
public String getReadme3() {
return readme3;
}
public void setReadme3(String readme3) {
this.readme3 = readme3;
}
public SearchMetadata getSearchMetadata() {
return searchMetadata;
}
public void setSearchMetadata(SearchMetadata searchMetadata) {
this.searchMetadata = searchMetadata;
}
public List<Status> getStatuses() {
return statuses;
}
public void setStatuses(List<Status> statuses) {
this.statuses = statuses;
}
public Aggregations getAggregations() {
return aggregations;
}
public void setAggregations(Aggregations aggregations) {
this.aggregations = aggregations;
}
}
Status.class
public class Status
{
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("text")
#Expose
private String text;
#SerializedName("link")
#Expose
private String link;
#SerializedName("id_str")
#Expose
private String idStr;
#SerializedName("source_type")
#Expose
private String sourceType;
#SerializedName("provider_type")
#Expose
private String providerType;
#SerializedName("retweet_count")
#Expose
private Integer retweetCount;
#SerializedName("favourites_count")
#Expose
private Integer favouritesCount;
#SerializedName("images")
#Expose
private List<Object> images = new ArrayList<Object>();
#SerializedName("images_count")
#Expose
private Integer imagesCount;
#SerializedName("audio")
#Expose
private List<Object> audio = new ArrayList<Object>();
#SerializedName("audio_count")
#Expose
private Integer audioCount;
#SerializedName("videos")
#Expose
private List<Object> videos = new ArrayList<Object>();
#SerializedName("videos_count")
#Expose
private Integer videosCount;
#SerializedName("place_name")
#Expose
private String placeName;
#SerializedName("place_id")
#Expose
private String placeId;
#SerializedName("place_context")
#Expose
private String placeContext;
#SerializedName("location_point")
#Expose
private List<Double> locationPoint = new ArrayList<Double>();
#SerializedName("location_radius")
#Expose
private Integer locationRadius;
#SerializedName("location_mark")
#Expose
private List<Double> locationMark = new ArrayList<Double>();
#SerializedName("location_source")
#Expose
private String locationSource;
#SerializedName("hosts")
#Expose
private List<String> hosts = new ArrayList<String>();
#SerializedName("hosts_count")
#Expose
private Integer hostsCount;
#SerializedName("links")
#Expose
private List<String> links = new ArrayList<String>();
#SerializedName("links_count")
#Expose
private Integer linksCount;
#SerializedName("mentions")
#Expose
private List<Object> mentions = new ArrayList<Object>();
#SerializedName("mentions_count")
#Expose
private Integer mentionsCount;
#SerializedName("hashtags")
#Expose
private List<Object> hashtags = new ArrayList<Object>();
#SerializedName("hashtags_count")
#Expose
private Integer hashtagsCount;
#SerializedName("without_l_len")
#Expose
private Integer withoutLLen;
#SerializedName("without_lu_len")
#Expose
private Integer withoutLuLen;
#SerializedName("without_luh_len")
#Expose
private Integer withoutLuhLen;
#SerializedName("user")
#Expose
private User user;
#SerializedName("provider_hash")
#Expose
private String providerHash;
#SerializedName("classifier_language")
#Expose
private String classifierLanguage;
#SerializedName("classifier_language_probability")
#Expose
private Double classifierLanguageProbability;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getIdStr() {
return idStr;
}
public void setIdStr(String idStr) {
this.idStr = idStr;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public String getProviderType() {
return providerType;
}
public void setProviderType(String providerType) {
this.providerType = providerType;
}
public Integer getRetweetCount() {
return retweetCount;
}
public void setRetweetCount(Integer retweetCount) {
this.retweetCount = retweetCount;
}
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
public List<Object> getImages() {
return images;
}
public void setImages(List<Object> images) {
this.images = images;
}
public Integer getImagesCount() {
return imagesCount;
}
public void setImagesCount(Integer imagesCount) {
this.imagesCount = imagesCount;
}
public List<Object> getAudio() {
return audio;
}
public void setAudio(List<Object> audio) {
this.audio = audio;
}
public Integer getAudioCount() {
return audioCount;
}
public void setAudioCount(Integer audioCount) {
this.audioCount = audioCount;
}
public List<Object> getVideos() {
return videos;
}
public void setVideos(List<Object> videos) {
this.videos = videos;
}
public Integer getVideosCount() {
return videosCount;
}
public void setVideosCount(Integer videosCount) {
this.videosCount = videosCount;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getPlaceContext() {
return placeContext;
}
public void setPlaceContext(String placeContext) {
this.placeContext = placeContext;
}
public List<Double> getLocationPoint() {
return locationPoint;
}
public void setLocationPoint(List<Double> locationPoint) {
this.locationPoint = locationPoint;
}
public Integer getLocationRadius() {
return locationRadius;
}
public void setLocationRadius(Integer locationRadius) {
this.locationRadius = locationRadius;
}
public List<Double> getLocationMark() {
return locationMark;
}
public void setLocationMark(List<Double> locationMark) {
this.locationMark = locationMark;
}
public String getLocationSource() {
return locationSource;
}
public void setLocationSource(String locationSource) {
this.locationSource = locationSource;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public Integer getHostsCount() {
return hostsCount;
}
public void setHostsCount(Integer hostsCount) {
this.hostsCount = hostsCount;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
public Integer getLinksCount() {
return linksCount;
}
public void setLinksCount(Integer linksCount) {
this.linksCount = linksCount;
}
public List<Object> getMentions() {
return mentions;
}
public void setMentions(List<Object> mentions) {
this.mentions = mentions;
}
public Integer getMentionsCount() {
return mentionsCount;
}
public void setMentionsCount(Integer mentionsCount) {
this.mentionsCount = mentionsCount;
}
public List<Object> getHashtags() {
return hashtags;
}
public void setHashtags(List<Object> hashtags) {
this.hashtags = hashtags;
}
public Integer getHashtagsCount() {
return hashtagsCount;
}
public void setHashtagsCount(Integer hashtagsCount) {
this.hashtagsCount = hashtagsCount;
}
public Integer getWithoutLLen() {
return withoutLLen;
}
public void setWithoutLLen(Integer withoutLLen) {
this.withoutLLen = withoutLLen;
}
public Integer getWithoutLuLen() {
return withoutLuLen;
}
public void setWithoutLuLen(Integer withoutLuLen) {
this.withoutLuLen = withoutLuLen;
}
public Integer getWithoutLuhLen() {
return withoutLuhLen;
}
public void setWithoutLuhLen(Integer withoutLuhLen) {
this.withoutLuhLen = withoutLuhLen;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getProviderHash() {
return providerHash;
}
public void setProviderHash(String providerHash) {
this.providerHash = providerHash;
}
public String getClassifierLanguage() {
return classifierLanguage;
}
public void setClassifierLanguage(String classifierLanguage) {
this.classifierLanguage = classifierLanguage;
}
public Double getClassifierLanguageProbability() {
return classifierLanguageProbability;
}
public void setClassifierLanguageProbability(Double classifierLanguageProbability) {
this.classifierLanguageProbability = classifierLanguageProbability;
}
}
User.java
public class User {
#SerializedName("screen_name")
#Expose
private String screenName;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("profile_image_url_https")
#Expose
private String profileImageUrlHttps;
#SerializedName("appearance_first")
#Expose
private String appearanceFirst;
#SerializedName("appearance_latest")
#Expose
private String appearanceLatest;
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfileImageUrlHttps() {
return profileImageUrlHttps;
}
public void setProfileImageUrlHttps(String profileImageUrlHttps) {
this.profileImageUrlHttps = profileImageUrlHttps;
}
public String getAppearanceFirst() {
return appearanceFirst;
}
public void setAppearanceFirst(String appearanceFirst) {
this.appearanceFirst = appearanceFirst;
}
public String getAppearanceLatest() {
return appearanceLatest;
}
public void setAppearanceLatest(String appearanceLatest) {
this.appearanceLatest = appearanceLatest;
}
}
Aggregations.class
public class Aggregations {
}
And finally, this is the code I use to read the JSON and store as JSON objects,
SharedPreferences Tempx = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
SharedPreferences.Editor edx = Tempx.edit();
edx.putString("GSON_FEED", response.toString());
edx.apply();
Gson gson = new Gson();
JsonParser parser = new JsonParser();
try{
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
}catch(Throwable e) {
JsonElement obj = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonObject();
MainPojo cse = gson.fromJson( obj , MainPojo.class);
TweetList.add(cse);
}
Though I am able to log the JSON as String, I don't know if I am storing it the wrong way, any help will be much appreciated, Thanks!
You could define a custom deserializer and register a type adapter with GSON. Also
why are you using this:
JsonArray jArray = parser.parse(Tempx.getString("GSON_FEED","")).getAsJsonArray();
.. when you intend to use GSON for deserialization? You could just do it in your deserializer.
https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization
EG:
public class FooDeserializer implements JsonDeserializer<Foos>
{
#Override public Foos deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject jsonObject = json.getAsJsonObject();
JsonArray statusArray = jsonObject.get("statuses").getAsJsonArray();
Foos result = new Foos();
ArrayList fooArray = new ArrayList<>;
for (JsonElement e : statusArray) {
fooArray.add(new Foo());
}
result.setFoos(fooArray);
return result;
}
}
I have an xml file with data (not complete xml file)
<header>
<ParameterContext>
<Parameter>
<Name>FILEID<Name>
<Value>1001445<Value>
</Parameter>
<Identifier>Id</Identifier>
</ParameterContext>
<ParameterContext>
<Parameter>
<Name>product</Name>
<Value>ECT</ns0:Value>
</Parameter>
<Identifier>ProductName</Identifier>
</ParameterContext>
</header>
please help me to store this xml data(data of parametercontext elements) in to arraylist.
Sorry for not posting this earlier.
I have 2 classes object and load
public class object{
private ArrayList<ParameterContext> parameterCtx = new ArrayList<ParameterContext>();
public ArrayList<ParameterContext> getParameterCtx() {
return parameterCtx;
}
public void setParameterCtx(ParameterContext parameterCtx) {
this.parameterCtx.add(parameterCtx) ;
}
public Parameter searchParameter(String name, String identifier, ArrayList<ParameterContext> al) {
for(int i = 0; i < al.size(); i++) {
if(al.get(i).getIdentifier().equalsIgnoreCase(identifier)) {
for(int j = 0; j < al.get(i).getParameter().size(); j++) {
if(al.get(i).getParameter().get(j).getName().equalsIgnoreCase(name) ) {
return al.get(i).getParameter().get(j);
}
}
}
}
return null ;
}
}
and
public class load{
#XmlElement(name = "ParameterContext")
protected List<load.ParameterContext> parameterContext;
public List<load.ParameterContext> getParameterContext() {
if (parameterContext == null) {
parameterContext = new ArrayList<load.ParameterContext>();
}
return this.parameterContext;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"parameter",
"identifier"
})
public static class ParameterContext {
#XmlElement(name = "Parameter", required = true)
protected List<load.ParameterContext.Parameter> parameter;
#XmlElement(name = "Identifier", required = true)
protected String identifier;
public List<load.ParameterContext.Parameter> getParameter() {
if (parameter == null) {
parameter = new ArrayList<load.ParameterContext.Parameter>();
}
return this.parameter;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String value) {
this.identifier = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"name",
"value"
})
public static class Parameter {
#XmlElement(name = "Name", required = true)
protected String name;
#XmlElement(name = "Value", required = true)
protected String value;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
when i use object.searchparameter("FIELD","ID",object.getParameterCtx()).getValue());
NULLPOINTEREXCEPTION is coming.(getparameterCtx is not initialized).Before this line I need to initialize it right.How to Initialize?
using JAXB, create a class that mimics the XML
#XmlRootElement(name="header")
public class XMLBean {
public List<ParameterContext> pc;
public XMLBean() {
}
public List<ParameterContext> getPc() {
return pc;
}
public void setPc(List<ParameterContext> pc) {
this.pc = pc;
}
}
public class ParameterContext {
public Parameter parameter;
public String identifier;
public ParameterContext() {
}
public Parameter getParameter() {
return pc;
}
public void setParameter(Parameter parameter) {
this.param = param;
}
public String getIdentifier() {
return identifer;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
}
public class Parameter {
public String name;
public String value;
public Parameter() {
}
public void setName(String name) {
this.name = name;
}
public void getName() {
return name;
}
public void setValue(String value) {
this.value = value;
}
public void getValue(String value) {
return value;
}
}
public static void main(String[] args) {
InputStream is = YOURXML
JAXBContext jaxb = JAXBContext.newInstace(XMLBean.class);
Unmarshaller jaxbUnmarshaller = jaxb.createUnmarshaller();
XMLBean xml = (XMLBean) jaxbUnmarshaller.unmarshal(is);
System.out.println(xml.getParameterContext().get(0).getParam().getName());
System.out.println(xml.getParameterContext().get(0).getParam().getValue());
}
something like that
If the xml elements are same and repetitive Create an object with the attributes as the elements with getter/setters. Parse the xml data and store the value in the object.