Json String to Java Object with dynamic key name - java

I'm trying to parse this structured of json string to Java Object but I failed every attempt.
{
"message": "Test Message",
"status": true,
"users": {
"user_xy": [
{
"time": "2016-08-25 19:01:20.944614158 +0300 EEST",
"age": 24,
"props": {
"pr1": 197,
"pr2": 0.75,
"pr3": 0.14,
"pr4": -0.97
}
}
],
"user_zt": [
{
"time": "2016-08-25 17:08:36.920891187 +0300 EEST",
"age": 29,
"props": {
"pr1": 1.2332131860505051,
"pr2": -0.6628148829634317,
"pr3": -0.11622442112006928
}
}
]
}
}
props field can contain 1 properties or 6 properties, it depends on db record. Also Username part dynamically changing.
Can I parse successfully this structured string with Jackson Lib?

You have to create calss structure like bellow to map your string to java object.
Create one class for Details
public class Details {
private String message;
private String status;
private Map<String, List<UserDetails>> users = new HashMap<String, List<UserDetails>>();
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Map<String, List<UserDetails>> getUsers() {
return users;
}
public void setUsers(Map<String, List<UserDetails>> users) {
this.users = users;
}
}
Create UserDetails class like bellow.
public class UserDetails {
private String time;
private String age;
private Map<String, String> prop = new HashMap<String, String>();
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Map<String, String> getProp() {
return prop;
}
public void setProp(Map<String, String> prop) {
this.prop = prop;
}
}
Now you can map your string with Details class.
Hope this will help..

public class Details {
private String message;
private boolean status;
Users UsersObject;
// Getter Methods
public String getMessage() {
return message;
}
public boolean getStatus() {
return status;
}
public Users getUsers() {
return UsersObject;
}
// Setter Methods
public void setMessage(String message) {
this.message = message;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setUsers(Users usersObject) {
this.UsersObject = usersObject;
}
}
public class Users {
ArrayList < Object > user_xy = new ArrayList < Object > ();
ArrayList < Object > user_zt = new ArrayList < Object > ();
// Getter Methods
// Setter Methods
}
You can also use online JSON to JAVA Object Converter : https://codebeautify.org/json-to-java-converter

Related

Unable to retrieve document - Castexception ParameterizedType

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?

Mapping a nested JSON response obtained using RxJava and Retrofit

I starting out with RxJava and Retrofit and wanted to create a simple app to show a list of 100 cryptocurrencies.
I am making an api call which results in something like this :
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
But all I want from this is "Response" and "Data". Since it is not practical to create a 100 different model classes for each coin, I want to store information of all the coins in a common class named Coin which would look something like this :
public class Coins {
#SerializedName("Algorithm")
private String mAlgorithm;
#SerializedName("CoinName")
private String mCoinName;
#SerializedName("FullName")
private String mFullName;
#SerializedName("FullyPremined")
private String mFullyPremined;
#SerializedName("Id")
private String mId;
#SerializedName("ImageUrl")
private String mImageUrl;
#SerializedName("Name")
private String mName;
#SerializedName("PreMinedValue")
private String mPreMinedValue;
#SerializedName("ProofType")
private String mProofType;
#SerializedName("SortOrder")
private String mSortOrder;
#SerializedName("Sponsored")
private Boolean mSponsored;
#SerializedName("Symbol")
private String mSymbol;
#SerializedName("TotalCoinSupply")
private String mTotalCoinSupply;
#SerializedName("TotalCoinsFreeFloat")
private String mTotalCoinsFreeFloat;
#SerializedName("Url")
private String mUrl;
public String getAlgorithm() {
return mAlgorithm;
}
public void setAlgorithm(String Algorithm) {
mAlgorithm = Algorithm;
}
public String getCoinName() {
return mCoinName;
}
public void setCoinName(String CoinName) {
mCoinName = CoinName;
}
public String getFullName() {
return mFullName;
}
public void setFullName(String FullName) {
mFullName = FullName;
}
public String getFullyPremined() {
return mFullyPremined;
}
public void setFullyPremined(String FullyPremined) {
mFullyPremined = FullyPremined;
}
public String getId() {
return mId;
}
public void setId(String Id) {
mId = Id;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String ImageUrl) {
mImageUrl = ImageUrl;
}
public String getName() {
return mName;
}
public void setName(String Name) {
mName = Name;
}
public String getPreMinedValue() {
return mPreMinedValue;
}
public void setPreMinedValue(String PreMinedValue) {
mPreMinedValue = PreMinedValue;
}
public String getProofType() {
return mProofType;
}
public void setProofType(String ProofType) {
mProofType = ProofType;
}
public String getSortOrder() {
return mSortOrder;
}
public void setSortOrder(String SortOrder) {
mSortOrder = SortOrder;
}
public Boolean getSponsored() {
return mSponsored;
}
public void setSponsored(Boolean Sponsored) {
mSponsored = Sponsored;
}
public String getSymbol() {
return mSymbol;
}
public void setSymbol(String Symbol) {
mSymbol = Symbol;
}
public String getTotalCoinSupply() {
return mTotalCoinSupply;
}
public void setTotalCoinSupply(String TotalCoinSupply) {
mTotalCoinSupply = TotalCoinSupply;
}
public String getTotalCoinsFreeFloat() {
return mTotalCoinsFreeFloat;
}
public void setTotalCoinsFreeFloat(String TotalCoinsFreeFloat) {
mTotalCoinsFreeFloat = TotalCoinsFreeFloat;
}
public String getUrl() {
return mUrl;
}
public void setUrl(String Url) {
mUrl = Url;
}
}
So finally my mapped response class would look like :
public class CoinsListResponse {
private boolean success;
private List<Coins> coinsList;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<Coins> getCoinsList() {
return coinsList;
}
public void setCoinsList(List<Coins> coinsList) {
this.coinsList = coinsList;
}
}
I haven't added #Serialized notations because I don't know what key to annotate it with.
My Retrofit service interface has a method to return the results to this map :
public interface CoinService {
#NonNull
#POST
Observable<CoinsListResponse> getCoinList();
}
Since, I am a starter with Retrofit and RxAndroid, there might be a better method to do this, which I am not aware of. If so, please mention that as well !! I am trying to get my head around this for days but couldn't find any answer on SO as well.
Please Help !!
Change
private List<Coins> coinsList;
to
#SerializedName("Data")
private Map<String, Coins> coinsByName;
You can then either just use coinsByName.values() or call e.g. coinsByName.get("LTC")

Java ; JSON ; Jackson ; Retrieving the value from a List inside an Array from JSON

I'm trying to read the values from a JSON URL, however I don't know how I can proceed with reading the values from a List inside of an Array? Below you will find my POJO, Main, and JSON code. Thank you so much for your help
POJO:
package org.jcexchange.FBApp;
import java.util.List;
import org.jcexchange.FBApp.Details;
public class Users {
private List<Details> Values;
public List<Details> getValues() {
return this.Values;
}
public void setValues(List<Details> Values) {
this.Values = Values;
}
}
public class Details {
private String user_name;
private String user_password;
private int age;
private String user_email;
public String getUserName() {
return this.user_name;
}
public void setUserName(String user_name) {
this.user_name = user_name;
}
public String getUserPassword() {
return this.user_password;
}
public void setUserPassword(String user_password) {
this.user_password = user_password;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserEmail() {
return this.user_email;
}
public void setUserEmail(String user_email) {
this.user_email = user_email;
}
}
Main:
public class Main {
public static void main(String[] args) {
try {
URL jsonURL = new URL("https://jchtest.herokuapp.com/index.php?
PW=2");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
Users[] a1 = mapper.readValue(jsonURL, Users[].class);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
I'm able to pull the JSON from a webservice, however I'm stuck trying to figure out how I could retrieve for instance the user_name from the first "Values" index of the JSON array
JSON:
[
{
"Values": {
"user_name": "jhart",
"user_password": "gooddeval1",
"age": 28,
"user_email": "heheh"
}
},
{
"Values": {
"user_name": "bdole",
"user_password": "Passwordd",
"age": 82,
"user_email": "hahah"
}
}
]
Well , it is a little confusing here may be because i dont have the full context. From the de-serializer you are telling me that i expect an Array of Users and then within each User i have a List of "Values" , but the JSON tells me that Values is a singular property for Users. Anyways , here is a sample that works on the assumption i have made. This can be fiddled around to change the collection and singular properties
import org.codehaus.jackson.annotate.JsonProperty;
public class Users {
#JsonProperty("Values")
private Details Values;
public Details getValues() {
return this.Values;
}
public void setValues(Details Values) {
this.Values = Values;
}
}
import org.codehaus.jackson.annotate.JsonProperty;
public class Details {
#JsonProperty("user_name")
private String user_name;
#JsonProperty("user_password")
private String user_password;
#JsonProperty("age")
private int age;
#JsonProperty("user_email")
private String user_email;
public String getUserName() {
return this.user_name;
}
public void setUserName(String user_name) {
this.user_name = user_name;
}
public String getUserPassword() {
return this.user_password;
}
public void setUserPassword(String user_password) {
this.user_password = user_password;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserEmail() {
return this.user_email;
}
public void setUserEmail(String user_email) {
this.user_email = user_email;
}
}
import java.net.URL;
import org.codehaus.jackson.map.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
URL jsonURL = new URL("https://jchtest.herokuapp.com/index.php?PW=2");
ObjectMapper mapper = new ObjectMapper();
Users[] a1 = mapper.readValue(jsonURL, Users[].class);
System.out.println(a1[0].getValues().getUserName());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
This prints "jhart" for me.
Please note : One thing you can try is based on the array/singular property you can populate the Object and write it as JSON. That way you can find what is different in what Jackson Deserializer expects vs What we are actually supplying.

Cannot Parse a JSON response that is received by RestTemplate

I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.
The request sent by the client was syntactically incorrect.
Code
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
MappingJackson2HttpMessageConverter());
ResponseEntity<Results> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Results.class);
System.err.println(">>" + responseEntity.getBody().getEvents().size());
Classes
Results
public class Results {
private List<Events> events;
getter and setter
}
Events
public class Event {
private long eventId;
private String name;
private String subTitle;
private String description;
private String localDate;
private String localDateFrom;
private String imageUrl;
private int venueId;
private String venue;
private int availableTickets;
private long performerId;
private String performer;
private String performerType;
private int subcategoryId;
private String urlCategoryName;
private String metaTitle;
private String metaDescription;
private String primeSportUrl;
private String sectionWiseView;
private String venueCity;
private String venueState;
private String snippetDate;
private int eiProductionId;
private boolean requireBillingAsShipping;
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalDateFrom() {
return localDateFrom;
}
public void setLocalDateFrom(String localDateFrom) {
this.localDateFrom = localDateFrom;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public int getAvailableTickets() {
return availableTickets;
}
public void setAvailableTickets(int availableTickets) {
this.availableTickets = availableTickets;
}
public long getPerformerId() {
return performerId;
}
public void setPerformerId(long performerId) {
this.performerId = performerId;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getPerformerType() {
return performerType;
}
public void setPerformerType(String performerType) {
this.performerType = performerType;
}
public int getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(int subcategoryId) {
this.subcategoryId = subcategoryId;
}
public String getUrlCategoryName() {
return urlCategoryName;
}
public void setUrlCategoryName(String urlCategoryName) {
this.urlCategoryName = urlCategoryName;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getPrimeSportUrl() {
return primeSportUrl;
}
public void setPrimeSportUrl(String primeSportUrl) {
this.primeSportUrl = primeSportUrl;
}
public String getSectionWiseView() {
return sectionWiseView;
}
public void setSectionWiseView(String sectionWiseView) {
this.sectionWiseView = sectionWiseView;
}
public String getVenueCity() {
return venueCity;
}
public void setVenueCity(String venueCity) {
this.venueCity = venueCity;
}
public String getVenueState() {
return venueState;
}
public void setVenueState(String venueState) {
this.venueState = venueState;
}
public String getSnippetDate() {
return snippetDate;
}
public void setSnippetDate(String snippetDate) {
this.snippetDate = snippetDate;
}
public int getEiProductionId() {
return eiProductionId;
}
public void setEiProductionId(int eiProductionId) {
this.eiProductionId = eiProductionId;
}
public boolean isRequireBillingAsShipping() {
return requireBillingAsShipping;
}
public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {
this.requireBillingAsShipping = requireBillingAsShipping;
}
}
Partial Response
[{
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
UPDATE
I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.
UPDATE
The code is returning following exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217)
at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45)
at com.myproject.web.TicketController.findTicket(TicketController.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
UPDATE
following code returns
Code
try {
System.err.println(">>> primeSport");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<Event[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",
Event[].class);
System.err.println(">>" + responseEntity.getBody().length);
System.err.println(">>" + responseEntity.getBody()[0].getEventId());
System.err.println(">>" + responseEntity.getBody()[1].getEventId());
} catch (Exception e) {
e.printStackTrace();
}
Output
>1532
>0
>0
Can you try the following and see whether helps:
ResponseEntity<Events[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Events[].class);
System.err.println(">>" + responseEntity.getBody().length);
For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.
#JsonProperty("EventId")
private long eventId;
#JsonProperty("Name")
private String name;
Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?
Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).
Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.
String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "username");
params.add("password", "password");
params.add("userid", "23");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
Please let me know, how it works out.
Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.
According to the json format, all you need is using the Event class instead of the Result class.
Or change the JSON result to this :
["events": {
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.writeValue(new File("c://temp/employee.json"), Results);
}

Create json object using java

I have tried several ways to create follwing format json using java. (Gson , Jackson , ...)
{
"outbound": {
"address": [
"t91",
"t0992"
],
"send": "t678",
"outMessage": {
"message": "Hello World"
},
"client": "156",
"receipt": {
"URL": "http://example.com/Delivery",
"callback": "some-to-the-request"
},
"senderName": "Inc."
}
}
Any help?
Use code below.
Create POJO
public class TestPojo {
private Outbound outbound;
public Outbound getOutbound() {
return outbound;
}
public void setOutbound(Outbound outbound) {
this.outbound = outbound;
}
}
class Outbound {
private String[] address;
private String send;
private OutMessage outMessage;
private Receipt receipt;
private String senderName;
public String[] getAddress() {
return address;
}
public void setAddress(String[] address) {
this.address = address;
}
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public OutMessage getOutMessage() {
return outMessage;
}
public void setOutMessage(OutMessage outMessage) {
this.outMessage = outMessage;
}
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
}
class OutMessage {
private String message;
public OutMessage(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
class Receipt {
private String URL;
private String callback;
public Receipt(String uRL, String callback) {
super();
URL = uRL;
this.callback = callback;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
}
Main Class (JSON to Object)
String json = "{'outbound':{'address':['t91','t0992'],'send':'t678','outMessage':{'message':'Hello World'},'receipt':{'URL':'http://example.com/Delivery','callback':'some-to-the-request'},'senderName':'Inc.'}}";
TestPojo testPojo = new Gson().fromJson(json, TestPojo.class);
System.out.println(testPojo.getOutbound().getSenderName());
Output
Inc.
Main Class (Object to JSON)
TestPojo testPojo = new TestPojo();
Outbound outbound = new Outbound();
outbound.setAddress(new String[]{"t91", "t0992"});
outbound.setOutMessage(new OutMessage("Hello World"));
outbound.setReceipt(new Receipt("http://example.com/Delivery", "some-to-the-request"));
outbound.setSenderName("Inc.");
outbound.setSend("t678");
testPojo.setOutbound(outbound);
System.out.println(new Gson().toJson(testPojo));
Output
{"outbound":{"address":["t91","t0992"],"send":"t678","outMessage":{"message":"Hello World"},"receipt":{"URL":"http://example.com/Delivery","callback":"some-to-the-request"},"senderName":"Inc."}}
Detail
Used GSON library.
Used a json given by you.

Categories