Specified object from JSONObject - java

I have JSONObject which contains as shown below and created class Markets contained all fields. I want put JSONObject elements to created object of Markets.
Example: Markets markets = new Markets(),then put elements from JSONObject to markets and I want to be able to get markets.getInstrumentName(). How can I do this ?
I try using Gson, like this Markets markets = gson2.fromJson(jsonObject, Markets.class); but there are different types and it is wrong way.
JSONObject:
{
"map": {
"netChange": -81.0,
"instrumentType": "INDICES",
"percentageChange": -1.31,
"scalingFactor": 1,
"epic": "IX.D.FTSE.DAILY.IP",
"updateTime": "00:02:48",
"updateTimeUTC": "23:02:48",
"offer": 6095.8,
"instrumentName": "FTSE 100",
"high": 6188.3,
"low": 6080.8,
"streamingPricesAvailable": true,
"marketStatus": "TRADEABLE",
"delayTime": 0,
"expiry": "DFB",
"bid": 6094.8
}
}
Markets:
class Markets {
private double bid;
private double offer;
private int delayTime;
private String epic;
private String expiry;
private double high;
private double low;
private String instrumentName;
private String instrumentType;
private String marketStatus;
private double netChange;
private double percentageChange;
private int scalingFactor;
private boolean streamingPricesAvailable;
private String updateTime;
private String updateTimeUTC;
//getters and setters
}

Using Jackson library
JSONObject jsonObject = //...
ObjectMapper mapper = new ObjectMapper();
Markets markets = mapper.readValue(jsonObject.toString(), Markets.class);

Here is sample Code when you want to convert JSON to object :
yourObject = new Gson().fromJson(yourJSONObject.toString(), YourObject.class);
I'm using Gson 2.4. and it works fine.
compile 'com.google.code.gson:gson:2.4'

Related

Long value is always null while using RestTemplate in Spring Boot

I am trying to parse this json
{
"total_count": 3,
"offset": 0,
"limit": 50,
"notifications": [
{
"isEdge": false,
"large_icon": "",
"priority": 10,
"queued_at": 1579590097,
"remaining": 0,
"send_after": 1579590097,
"completed_at": 1579590110,
"small_icon": "",
"successful": 1,
"received": 1,
"tags": null,
"filters": null,
"template_id": null,
"ttl": null,
"url": "",
"contents": {
"en": "MoMo House presents MoMo eating competition. Come join us on Jan 26th
for the biggest MoMo eating competition ever."
}
"web_url": null,
"app_url": null,
"web_buttons": null,
"web_push_topic": null,
"wp_sound": "",
"wp_wns_sound": "",
"ios_attachments": null
}
]
}
This is my code to parse it
public ResponseEntity<HashMap<String,List<Notification>>> getAllNotifications(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Authorization",Constants.ONESIGNAL_REST_KEY);
HttpEntity<String> entity = new HttpEntity<String>("body", httpHeaders);
ResponseEntity<OneSignalResponse> oneSignalResponseResponseEntity = restTemplate.exchange(Constants.ONESIGNAL_URL, HttpMethod.GET,entity,OneSignalResponse.class);
OneSignalResponse oneSignalResponse=oneSignalResponseResponseEntity.getBody();
System.out.println("Title "+oneSignalResponse.getNotifications().get(0).getHeadings().getEn());
List<Notification> notifications = new ArrayList<>();
for(NotificationsItem oneSig : oneSignalResponse.getNotifications()){
Notification notification = new Notification();
notification.setId(oneSig.getId());
notification.setTitle(oneSig.getHeadings().getEn());
notification.setMessage(oneSig.getContents().getEn());
System.out.println("value of sent time "+oneSig.getCompletedAt()); //this is null
Date date = new Date(sentTime);
notification.setDate(localDateTime.toString());
notifications.add(notification);
}
HashMap<String,List<Notification>> hashMap = new HashMap<>();
hashMap.put("notifications",notifications);
return new ResponseEntity<>(hashMap, HttpStatus.OK);
}
And this is my POJO
public class NotificationsItem{
#SerializedName("isEdge")
private boolean isEdge;
#SerializedName("delayed_option")
private String delayedOption;
#SerializedName("queued_at")
private int queuedAt;
#SerializedName("failed")
private int failed;
#SerializedName("priority")
private int priority;
#SerializedName("remaining")
private int remaining;
#SerializedName("tags")
private Object tags;
#SerializedName("canceled")
private boolean canceled;
#SerializedName("chrome_icon")
private String chromeIcon;
#SerializedName("completed_at")
private Object completedAt;
#SerializedName("isWP")
private boolean isWP;
#SerializedName("send_after")
private int sendAfter;
#SerializedName("adm_sound")
private String admSound;
#SerializedName("chrome_web_image")
private String chromeWebImage;
#SerializedName("contents")
private Contents contents;
#SerializedName("converted")
private int converted;
#SerializedName("android_visibility")
private int androidVisibility;
#SerializedName("headings")
private Headings headings;
#SerializedName("adm_group")
private String admGroup;
#SerializedName("chrome_web_badge")
private String chromeWebBadge;
#SerializedName("spoken_text")
private SpokenText spokenText;
#SerializedName("ios_badgeCount")
private int iosBadgeCount;
#SerializedName("isChrome")
private boolean isChrome;
#SerializedName("alexa_ssml")
private Object alexaSsml;
#SerializedName("alexa_display_title")
private Object alexaDisplayTitle;
#SerializedName("android_accent_color")
private String androidAccentColor;
#SerializedName("android_group")
private String androidGroup;
#SerializedName("include_external_user_ids")
private Object includeExternalUserIds;
#SerializedName("isAdm")
private boolean isAdm;
#SerializedName("successful")
private int successful;
#SerializedName("web_push_topic")
private Object webPushTopic;
#SerializedName("adm_large_icon")
private String admLargeIcon;
#SerializedName("content_available")
private boolean contentAvailable;
#SerializedName("adm_small_icon")
private String admSmallIcon;
#SerializedName("buttons")
private Object buttons;
#SerializedName("app_url")
private Object appUrl;
#SerializedName("ios_badgeType")
private String iosBadgeType;
#SerializedName("delivery_time_of_day")
private String deliveryTimeOfDay;
#SerializedName("large_icon")
private String largeIcon;
#SerializedName("big_picture")
private String bigPicture;
#SerializedName("filters")
private Object filters;
#SerializedName("ttl")
private Object ttl;
#SerializedName("url")
private String url;
#SerializedName("include_player_ids")
private Object includePlayerIds;
#SerializedName("android_led_color")
private String androidLedColor;
#SerializedName("isWP_WNS")
private boolean isWPWNS;
#SerializedName("web_url")
private Object webUrl;
#SerializedName("adm_group_message")
private AdmGroupMessage admGroupMessage;
#SerializedName("adm_big_picture")
private String admBigPicture;
#SerializedName("small_icon")
private String smallIcon;
#SerializedName("template_id")
private Object templateId;
#SerializedName("web_buttons")
private Object webButtons;
#SerializedName("isAndroid")
private boolean isAndroid;
#SerializedName("isIos")
private boolean isIos;
#SerializedName("errored")
private int errored;
//getters setters
}
As the json is large I have included only those that matters and the POJO might not be accordingly here.
So when I call the method, I get the value of contents but I get null when I try to get completedAt this is shown as comment in the code too. So I am able to parse some parts perfectly but I am not able to parse some. I don't know what I am doing wrong so any help would be highly appreciated. Thanks
#SerializedName is a Gson annotation. Spring normally uses Jackson. The Jackson annotation for this would be #JsonProperty("name").
You have to change the datatype for the variable completedAt
#SerializedName("completed_at")
private Object completedAt;
To
#SerializedName("completed_at")
private Long completedAt;

GSON not parsing nested JSON objects properly

I have some data in the form of JSON, and was using the GSON library to parse it into a Java object to be used in later portions of the code. The JSON has nested objects, which don't seem to be getting parsed properly, and I can't figure out why, as the outer object is being converted as desired. Here is an example of the JSON data I'm looking at:
{
"title":"Emergency Services Headquarters",
"description":"",
"cid":"C70856",
"building_id":"4714",
"building_number":"3542",
"campus_code":"20",
"campus_name":"Busch",
"location":{
"name":"Emergency Services Headquarters",
"street":"129 DAVIDSON ROAD",
"additional":"",
"city":"Piscataway",
"state":"New Jersey",
"state_abbr":"NJ",
"postal_code":"08854-8064",
"country":"United States",
"country_abbr":"US",
"latitude":"40.526306",
"longitude":"-74.461470"
},
"offices":[
"Emergency Services"
]
}
I used codebeautify to create the Java object classes required for the JSON (everything is within Building.java):
public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location LocationObject;
ArrayList < Object > offices = new ArrayList < Object > ();
//Setters and getters have been omitted
}
class Location {
private String name;
private String street;
private String additional;
private String city;
private String state;
private String state_abbr;
private String postal_code;
private String country;
private String country_abbr;
private String latitude;
private String longitude;
//Setters and getters have been omitted
}
Here is the code I'm using to parse the JSON, where the variable json is an input parameter for the method:
Gson obj = new Gson();
JsonArray buildingsArray = new JsonArray();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
buildingsArray = jsonElement.getAsJsonArray();
for (int i = 0; i < buildingsArray.size(); i++)
Building building = obj.fromJson(buildingsArray.get(i), Building.class);
When I call methods such as building.getTitle() or building.getCid(), I get the appropriate values, however when I do building.getLocation() (where Location is a separate object), the code returns null. I have not been able to figure it out, is it an issue with the way GSON works? Or am I doing something wrong in my code?
First of all, change:
Location LocationObject;
to:
private Location location;
And, you can deserialise JSON much easier:
Gson gson = new GsonBuilder().create();
Building building = gson.fromJson(json, Building.class);
Json property name should match your POJO class properties, it should be location not LocationObject
public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location location;
ArrayList < Object > offices = new ArrayList < Object > ();
//Setters and getters have been omitted
}
It seems that you have a bad naming. Your location object in Building class is called LocationObject when your object inside JSON is called location.

Map JSON to pojo using Jackson for List that have different parameters

JSON FORMAT:
[
{
"0":
{
"cast":"",
"showname":"woh pagle",
"type":"Episodes"
},
"video":[
{
"src":"video.mp4"
},
{
"DRM":"False"
}
]
}
]
Here problem is I am getting below exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize
instance of java.util.ArrayList out of START_OBJECT token at [Source:
java.io.StringReader#1c9ca1; line: 1, column: 55617] (through
reference chain:
com.apalya.myplex.valueobject.ThirdPartyContentDetailsArray["video"])
My pojo classes are :
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonProperty("0")
private ThirdPartySubContentDetails subContent;
#JsonProperty("video")
private List<ThirdPartySubContentVideoInfo> video;
My Sub class pojo is :
private String src;
#JsonIgnore
#JsonProperty("DRM")
private String drm;
Please help me to write a pojo for that video list.
Your json starts as an array and not as an Object. The important part to change is how the Objectmapper should generate your json. For returning a List you need to do it this way:
List<FirstJson> jsonList = mapper.readValue(json, new TypeReference<List<FirstJson>>(){});
Here is my short working test I implement locally:
public static void main(String[] args) {
String json = "[{\"0\":{\"cast\":\"\",\"showname\":\"wohpagle\",\"type\":\"Episodes\"},\"video\":[{\"src\":\"video.mp4\"},{\"DRM\":\"False\"}]}]";
ObjectMapper mapper = new ObjectMapper();
List<FirstJson> jsonList = mapper.readValue(json, new TypeReference<List<FirstJson>>(){});
System.out.println(jsonList.toString());
}
The first part of your JsonArray in Pojo.(Named it FirstJson)
public class FirstJson{
#JsonProperty("0")
private FirstJson subContent;
private String cast;
private String showname;
private String type;
#JsonProperty("video")
private List<Video> videos;
//getter/setter
And the Video Pojo:
public class Video {
private String src;
#JsonProperty("DRM")
private String drm;
//getter/setter
Just a sidenote: If you declare your pojos in the same class file, the classes should be static. public static class FirstJson
According to the JSON structure described in the question, the following should be the POJOs:
public class MainPojo
{
#JsonProperty("0")
private ThirdPartySubContentDetails subContent;
#JsonProperty("video")
private List<ThirdPartySubContentVideoInfo> video;
// Getters and Setters for subContent and video
}
class ThirdPartySubContentDetails
{
private String cast;
private String showName;
private String type;
// Getters and Setters for cast, showName and type
}
#JsonIgnoreProperties(ignoreUnknown = true)
class ThirdPartySubContentVideoInfo
{
#JsonProperty("src")
private String src;
#JsonProperty("DRM")
private String drm;
// Getters and Setters for src and drm
}
You should call the deserializer method as follows:
List<MainPojo> list = new ObjectMapper().readValue(json, new TypeReference<List<MainPojo>>(){});

Gson to POJO, how to read the inner JSON Objects as part of the same POJO?

I have a JSON like below and would like to convert it using Gson to one POJO.
I am trying to figure out how to basically cut down the inner nested objects like desc to be treated as part of the same Java object, instead of creating a new POJO named Desc.
Is there a way to do this with Serialized Names to look into nested JSON objects?
Thanks in advance!
JSON to be converted to POJO
{
'name': name,
'desc': {
'country': country,
'city': city,
'postal': postal,
'street': street,
'substreet': substreet,
'year': year,
'sqm': sqm
},
'owner': [owner],
'manager': [manager],
'lease': {
'leasee': [
{
'userId': leaseeId,
'start': leaseeStart,
'end': leaseeeEnd
}
],
'expire': leaseExpire,
'percentIncrease': leasePercentIncrease,
'dueDate': dueDate
},
'deposit': {
'bank': 'Sample Bank',
'description': 'This is a bank'
}
}
Custom POJO
public class Asset {
private String mId;
#SerializedName("name")
private String mName;
private String mCountry;
private String mCity;
private String mPostal;
private String mStreet;
private String mSubstreet;
private int mYear;
private int mSqm;
#SerializedName("owner")
private List<String> mOwners;
#SerializedName("manager")
private List<String> mManagers;
private List<Leasee> mLeasees;
private DateTime mLeaseExpiration;
private int mPercentIncrease;
private int mDueDate;
private String mDepositBank;
private String mDepositDescription;
}

Convert multi type of lists into json using gson

How can I use gson to convert my object into json.I have two array lists in my object.I know the convertion if there is a single array list in the object by giving the type at gson.toJson(Object.class,).
Here my problem is I have two array lists which are related to two different objects.
Here is my object:
public class Profile
{
private String doctor_id;
private String name;
private String location;
private String phone;
private String minimum_amount;
private String minimum_slot;
private List<specialties> specialties;
private List<education> education;
}
public class specialties {
private String specialty_id;
private String specialization;
private List<super_specialties> super_specialties;
}
public class super_specialties {
private String super_specialty_id;
private String super_specialization;
}
public class education {
private String qualification;
private String yearOfCompletion;
}
Please guid me how to use gson to convert this object into json.
Thanks,
Chaitanya.K
Have you tried this.
Hope it help. Worked for me.
Gson gson = new Gson();
String obj = gson.toJson(ProfileClassObject);
System.out.println(obj);
This obj variable has the Json which you want.

Categories

Resources