I have a json response from an external API in below format.But I am not sure how to convert this to a POJO to get all these values separately later in the application
{
"count": 1,
"item_list": [
{
"property_value_map": {
"Data": {
"content_type": "image/jpeg",
"data": "ZJRgABAAEASABIAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS"
},
"DataType": 0,
"LastChanged": "2015-12-11T17:21:15+00:00",
"ObjectType": 1,
"PersonID": 1384
}
}
],
"page_number": 1,
"page_size": 20,
"total_items": 1,
"total_pages": 1,
"type_name": "Lnl_MultimediaObject",
"version": "1.0"
}
I created a POJO as below and its converting this JSON. But the issue is I dont know how to get the value for "data" from above JSON as my item_list is Object
public class GetInstancesResponseVO {
private int count;
private List<Object> item_list;
private int page_number;
private int page_size;
private int total_items;
private int total_pages;
private String type_name;
private String version;
public GetInstancesResponseVO() {}
/***Getters Setters **/
}
UPDATE
Tried with a pojo as suggested by Jaume Morón i Tarrasa
public class GetInstancesResponseVO {
private int count;
private List<PropertyValueMap> item_list;
private int page_number;
private int page_size;
private int total_items;
private int total_pages;
private String type_name;
private String version;
/***CONSTRUCTOR, SETTERS, GETTERS***/
}
But I am getting null . Here is my PropertyValueMap POJO;
public class PropertyValueMap {
private MyData Data;
private int DataType;
private String LastChanged;
private String ObjectType;
private String PersonID;
public PropertyValueMap() {}
/***GETTERS,SETTERS**/
}
And the Data POJO;
public class MyData implements Serializable{
private String content_type;
private String data;
public MyData() {}
/***GETTERS, SETTERS**/
}
I tried Data as String in PropertValueMap POJO and in either way I am getting null as below;
{
"count": 1,
"item_list": [
{
"objectType": null,
"data": null,
"personID": null,
"lastChanged": null,
"dataType": 0
}
],
"page_number": 1,
"page_size": 20,
"total_items": 1,
"total_pages": 1,
"type_name": "Lnl_MultimediaObject",
"property_value_map": null,
"version": "1.0"
}
And also the JSON response does not look like right as its missing "property_value_map". A help would be greatly appreciated as I am going to waste yet another day for it.
Related
I obtain data with GET method and try to fed them to PUT method.
And I get a bad request error.
But when I edit the JSON as below then everithing works fine.
So why does the first JSON not work?
Controller class:
#RestController
#RequestMapping("/api")
public class FileController {
private final FileService fileService;
private final DocService docService;
private final DraftFileToPresentationConverter draftFileToPresentationConverter;
#Autowired
private DocFileRelationRepository docFileRelationRepository;
#Autowired
public FileController(FileService fileService,
DocService docService,
DraftFileToPresentationConverter draftFileToPresentationConverter) {
this.fileService = fileService;
this.docService = docService;
this.draftFileToPresentationConverter = draftFileToPresentationConverter;
}
#GetMapping("/docs/files/{id}")
public ResponseEntity<FilePresentation> getDraftFile(#PathVariable Long id) {
DraftFile file = fileService.getFile(id);
FilePresentation filePresentation = draftFileToPresentationConverter.convert(file);
return new ResponseEntity<>(filePresentation, HttpStatus.OK);
}
#PutMapping("/docs/files/{id}")
public ResponseEntity<FilePresentation> updateDraftFile(#RequestBody FilePresentation filePresentation) {
fileService.update(draftFileToPresentationConverter.convert(filePresentation));
return new ResponseEntity<>(filePresentation, HttpStatus.OK);
}
DTO:
#Data
public class FilePresentation {
private Long id;
private States state;
private String name;
private String user;
private Date dateUpload;
private Long lenght;
private IdRef document;
private IdRef judgeDoc;
public String getSize()
{
Double result = Double.valueOf(lenght/1024.0/1024.0);
if(result<1)
{
result = Double.valueOf(lenght/1024.0);
if(result<1)
{
return (lenght + " байт");
}
return (result.intValue() + " Кбайт");
}
return (result.intValue() + " Мбайт");
}
}
Troublesome class:
#Data
public class IdRef {
public IdRef(Long id) {
this.id = id;
}
private Long id;
}
JSON that I get with GET method and try to fed to PUT method (and get 400 Bad Request):
{
"id": 21,
"state": "DRAFT",
"name": "DNS-list.tiff",
"user": "JSmith",
"dateUpload": null,
"lenght": 28,
"document": {
"id": 141
},
"judgeDoc": null,
"size": "28 байт"
}
JSON that DOES work
{
"id": 21,
"state": "DRAFT",
"name": "DNS-list.tiff",
"user": "JSmith",
"dateUpload": null,
"lenght": 28,
"document": 141,
"judgeDoc": null,
"size": "28 байт"
}
Try to update RequestBody with #PathVariable
The constructor in IdRef was the reason.
I removed the constructor and it works fine now, my controller consumes the first JSON without errors.
With reference to this guide:
https://spring.io/guides/gs/consuming-rest/
The guide shows how to consume a RESTful web service.
The response from the REST API query results in the following JSON:
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
It creates a domain class called Quote.java to contain the data in the response:
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
My questions is how do I represent the following json:
{
"size": 1,
"limit": 25,
"isLastPage": true,
"values": [
{
"user": {
"name": "jcitizen",
"emailAddress": "jane#example.com",
"id": 101,
"displayName": "Jane Citizen",
"active": true,
"slug": "jcitizen",
"type": "NORMAL"
},
"permission": "ADMIN"
}
],
"start": 0
}
The outer objects like size and limit are straightforward but I can't figure out how to represent the values object, which looks like an array of json objects.
This should work.
class Output {
private String size,
private int limit;
private boolean isLastPage,
private List<Value> values;
private int start ;
}
class Value
{
User user,
private String permission;
}
class User {
private String name,
private String emailAddress,
private int id,
private String displayName,
private boolean active,
private String slug,
private String type
}
I am new to Gson parsing ,did some examples , but this time my json is much complex it looks like this
{
"message": "Ok",
"code": 200,
"data": {
"storage": {
"39": {
"weight": 22000,
"verificationPackageRequested": null,
"id": 39,
"countryCode": "US",
"photosPackageRequested": null,
"created": "2014-12-30 11:27:57",
"ItemPrice": 224.99,
"ItemTitle": "Apple iPad Mini MF432LL/A (16GB, Wi-Fi, Space Gray )",
"PhotoThumbnail": "/upload/storage-products/b8c2839010a8c5aae21df3b9e57125d0_photoThumbnail.jpg"
"items": [
{
"weight": 22000,
"verificationPackageRequested": null,
"id": 39,
"countryCode": "US",
"photosPackageRequested": null,
"created": "2014-12-30 11:27:57",
"ItemPrice": 224.99,
"ItemTitle": "Apple iPad Mini MF432LL/A (16GB, Wi-Fi, Space Gray )",
"PhotoThumbnail": "/upload/storage-products/b8c2839010a8c5aae21df3b9e57125d0_photoThumbnail.jpg"
}
],
"cellStatus": null,
"orderStorageIsMfPackage": 0,
"storageImage": "/upload/storage/storage_6_thumbnail.jpg"
}
}
},
"error": false
}
i tried this way
static class Page{
String message;
int code;
Data data;
//getters+setters
}
static class Data{
HashMap<Values,String> storage;
}
static class Values{
String PhotoThumbnail;
String ItemTitle;
String showPrice;
String weight;
String symbol;
String created;
String id;
String photosPackageRequested;
String verificationPackageRequested;
String countryCode;
//getters+setters
#Override
public String toString(){
return PhotoThumbnail+ " - "+ItemTitle+" - "+showPrice+" - "+weight+" - "+symbol+" - "+created+" - "+id+" - "+photosPackageRequested+" - "+verificationPackageRequested+" -"+countryCode;
}
}
}
And pass results like this
Gson gson = new GsonBuilder().create();
Page wp=gson.fromJson(json,Page.class) ;
But all the i can't get it to work , it show storage as null , i can't understand why , plsease help
It is because you have 39 item:
data
'-storage
'-39
'-items [item...]
If you change the "39" by "changeIT" for example:
...
"data": {
"storage": {
"changeIT": {
"orderStorageIsAlone": 1,
...
You can use model:
static class Wrapper {
Data data;
}
static class Data {
Storages storage;
}
static class Storages {
ChangeIT changeIT;
}
static class ChangeIT {
List<RItems> items;
public ChangeIT() {
items = new ArrayList<>();
}
}
static class RItems {
String PhotoThumbnail;
String ItemTitle;
String showPrice;
String weight;
String symbol;
String created;
String id;
String photosPackageRequested;
String verificationPackageRequested;
String countryCode;
...
(This is an example)
You can not use numbers as Class name, so I don't know how to map a transient element.
I'm trying to serialize to serialize the json string I have included below.
{
"mood": {
"is_featured": true,
"description": null,
"title": "2014 ",
"ordering": null,
"is_recently_modified": true,
"is_test": false,
"tracks": [
{
"album": {
"release_date": "2014-11-06",
"id": 359778,
"name": "Amansız Gücenik"
},
"name": "Hırpalandı Mayıs",
"artist": {
"id": 491169,
"name": "Ceylan Ertem"
},
"duration": 227,
"isrc": "TRA161400207",
"id": 3903997
},
{
"album": {
"release_date": "2013-08-05",
"id": 329129,
"name": "For Fuld Musik - 25 Danske Sommer Pop & Rock Hits Vol. 2"
},
"name": "Am I Wrong",
"artist": {
"id": 755957,
"name": "Nico & Vinz"
},
"duration": 387,
"isrc": "NO2G31301011",
"id": 3655085
}
],
"image_url": "some_url",
"is_recently_created": true,
"id": 128
}
}
I'm using this gson call to serialize it
Mood mood = new Gson().fromJson(result, Mood.class);
My class structers are like this.
public class Mood {
private boolean is_featured;
private boolean is_recently_modified;
private boolean is_recently_created;
private boolean is_test;
private String description;
private String title;
private String image_url;
private int id;
private int ordering;
private Track[] tracks;
public static class MoodContainer {
public Mood[] moods;
}
}
public class Track {
//variables
private Album album;
private Artist artist;
private Provider provider;
private String secure_url;
private String name;
private String region;
private String isrc;
private int duration;
private int track_order;
private int id;
}
And it goes on like this for any additional class variable. When I try to use the above call I end up with objects that have all null values. One thing to notice is some fields are not supplied in json string because different api calls supply different parts of these json strings. What I am doing wrong?
Root JSON object you provided has property mood - so you either have two options for deserialization to work properly:
Wrap your Mood class inside another object like this:
public class MoodWrapper { private Mood mood; }
and change de-serialization code to
MoodWrapper moodWrapper = new Gson().fromJson(result, MoodWrapper.class);
Skip a root object when deserializing:
final Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
Mood mood = gson.fromJson(rootObj.getAsJsonObject("mood"), Mood.class);
The top-level elements in the JSON string should be your object's properties, not the outer element "mood" which you have.
I have a JSON file that I fetch from the internet which contains schedule data for a TV channel. Nested within that file, alongside lots of metadata, is info about each broadcast (i.e. each programme) and below is a sample of that file:
For ease of understanding, I recommend this visual representation of the below JSON instead (click on the Viewer tab on the JSON viewer).
{
"schedule": {
"service": {
"type": "tv",
"key": "bbcnews",
"title": "BBC News Channel"
},
"day": {
"date": "2013-11-15",
"has_next": 1,
"has_previous": 1,
"broadcasts": [
{
"is_repeat": false, <=== This is the 1st broadcast programme
"is_blanked": false,
"pid": "p01ks4z3",
"start": "2013-11-15T03:45:00Z",
"end": "2013-11-15T04:00:00Z",
"duration": 900,
"programme": {
"type": "episode",
"pid": "b03hdhhp",
"position": null,
"title": "15/11/2013",
"short_synopsis": "All the latest sports news and results from around the globe.",
"media_type": "audio_video",
"duration": 900,
"display_titles": {
"title": "Sport Today",
"subtitle": "15/11/2013"
},
"first_broadcast_date": "2013-11-15T03:45:00Z",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
},
"programme": {
"type": "brand",
"pid": "b0121xvw",
"title": "Sport Today",
"position": null,
"expected_child_count": null,
"first_broadcast_date": "2011-06-13T02:45:00+01:00",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
}
},
"is_available_mediaset_pc_sd": false,
"is_legacy_media": false
}
},
{
"is_repeat": false, <=== This is the 2nd broadcast programme
"is_blanked": false,
"pid": "p01ks4z4",
"start": "2013-11-15T04:00:00Z",
"end": "2013-11-15T04:30:00Z",
"duration": 1800,
"programme": {
"type": "episode",
"pid": "b03hdhhs",
"position": null,
"title": "15/11/2013",
"short_synopsis": "Twenty-four hours a day, the latest national and international stories as they break.",
"media_type": "audio_video",
"duration": 1800,
"display_titles": {
"title": "BBC News",
"subtitle": "15/11/2013"
},
"first_broadcast_date": "2013-11-15T04:00:00Z",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
},
"programme": {
"type": "brand",
"pid": "b006mgyl",
"title": "BBC News",
"position": null,
"expected_child_count": null,
"first_broadcast_date": "2006-11-01T13:00:00Z",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
}
},
"is_available_mediaset_pc_sd": false,
"is_legacy_media": false
}
}
]
}
}
}
Using the answer to this question on StackOverflow, I created a Javabean class like so:
private class ScheduleData {
private Schedule schedule;
// create getter & setter
public static class Schedule {
private Service service;
private Day day;
// create getter & setter
}
public static class Service {
private String type;
private String key;
private String title;
// create getter & setter
}
public static class Day {
private String date;
private String has_next;
private String has_previous;
private Broadcasts broadcasts;
// create getter & setter
}
public static class Broadcasts {
private String is_repeat;
private String is_blanked;
private String pid;
private String time;
private String end;
private String duration;
private OuterProgramme programme;
// create getter & setter
}
public static class OuterProgramme {
private String type;
private String pid;
private String position;
private String title;
private String short_synopsis;
private String media_type;
private String duration;
private String first_broadcast_date;
private DisplayTitles display_titles;
private Ownership ownership;
private InnerProgramme programme;
// create getter & setter
}
public static class DisplayTitles {
private String title;
private String subtitle;
// create getter & setter
}
public static class Ownership {
private Service service;
// create getter & setter
}
public static class Service {
private String type;
private String id;
private String key;
private String title;
// create getter & setter
}
public static class InnerProgramme {
private String type;
private String pid;
private String title;
private String position;
private String expected_child_count;
private String first_broadcast_date;
private Ownership ownership;
private String is_available_mediaset_pc_sd;
private String is_legacy_media;
// create getter & setter
}
}
In my activity file, how do I loop through each broadcast node of the fetched JSON and retrieve programme data such as short_synopsis or display_titles and pass these into a custom listview display?
1) Define root Json Wrapper class ScheduleData.java
public class ScheduleData {
private Schedule schedule;
public Schedule getSchedule() {
return schedule;
}
}
2) Define its properties as seperate public classes:
2.a) Schedule.java
public class Schedule {
private Service service;
private Day day;
// TODO: create other getters & setters if you need
public Day getDay() {
return day;
}
}
2.b) Service.java
public class Service {
private String type;
private String id;
private String key;
private String title;
// TODO: create getters & setters if you need
}
2.c) Day.java
public class Day {
private String date;
private int has_next;
private int has_previous;
private Broadcast[] broadcasts;
// TODO: create other getters & setters if you need
public Broadcast[] getBroadcasts() {
return broadcasts;
}
}
2.d) Broadcast.java
public class Broadcast {
private boolean is_repeat;
private boolean is_blanked;
private String pid;
private String start;
private String end;
private int duration;
private Programme programme;
// TODO: create other getters & setters if you need
public Programme getProgramme() {
return programme;
}
}
2.e) Programme.java
public class Programme {
private String type;
private String pid;
private String position;
private String title;
private String short_synopsis;
private String media_type;
private int duration;
private String first_broadcast_date;
private DisplayTitle display_titles;
private Ownership ownership;
private Programme programme;
// TODO: create other getters & setters if you need
public String getShort_synopsis() {
return short_synopsis;
}
public DisplayTitle getDisplay_titles() {
return display_titles;
}
}
2.f) DisplayTitle.java
public class DisplayTitle {
private String title;
private String subtitle;
// create getter & setter
}
2.g) Ownership.java
public class Ownership {
private Service service;
// create getter & setter
}
3) Define an AsyncTask and call json service. Get result as stream and set its value to a ScheduleData instance using gson library. (I assume you know how to call json service on android, but if you don't it is a 5 min googling issue.)
HttpEntity getResponseEntity = getResponse.getEntity();
InputStream source = getResponseEntity.getContent();
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ScheduleData scheduleData = gson.fromJson(reader, ScheduleData.class);
4) Now you have a ScheduleData instance. It is filled by service's json response.
Schedule schedule = scheduleData.getSchedule();
Day day = schedule.getDay();
Broadcast[] broadCastArr = day.getBroadcasts();
// TODO: use your broadCastArr in an adapter