Recieve json array from api in angular2 - json

I'm trying to receive a json array from an api and display it on page, i'm fairly certain that something is wrong with my service, i just don't know what.
getAuctions(): Promise<Auction[]> {
return this.http.get(this.auctionsUrl)
.toPromise()
.then(response => response.json().array as Auction[])
.catch(this.handleError);
}
here is a response example
[
{
"id": 1,
"name": "Antik stol",
"description": "En fin antik stol från 1800-talet",
"startTime": "2016-12-13T10:00:00",
"endTime": "2017-02-23T10:00:00",
"imageUrl": "https://thumbs.dreamstime.com/z/antik-stol-som-stoppas-i-sammet-32935346.jpg",
"categoryId": 1,
"supplierId": 2,
"buyNowPrice": 8000,
"sold": true
},
{
"id": 2,
"name": "Antikt bord",
"description": "En fint antikt bord",
"startTime": "2016-12-10T10:00:00",
"endTime": "2017-03-29T10:00:00",
"imageUrl": "http://precisensan.com/antikforum/attachment.php?attachmentid=78277&stc=1&d=1292057973",
"categoryId": 1,
"supplierId": 1,
"buyNowPrice": 18000,
"sold": false
}
]

AuctionService:
getAuctions() : Observable<Auction[]> {
return this.http.get(this.auctionsUrl)
.map((response: Response) => response.json())
.catch(this.handleError)
}
AuctionComponent:
getAuctions(): void {
this.auctionService.getAuctions()
.subscribe(auctions => this.auctions = auctions);
}

Related

Unable to get the length of JSON object

I am getting 'TypeError: Cannot convert undefined or null to object' while trying to access the length of json object in nodejs.
Following is how my data looks like:
{
"college": [
{
"colleges": [],
"department": [
1,
2,
3
],
"general_course": [],
"id": 1,
"name": "College of the Arts",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1919"
},
{
"colleges": [],
"department": [
4,
5,
6
],
"general_course": [],
"id": 2,
"name": "College of Communications",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1920"
},
{
"colleges": [],
"department": [
7,
12
],
"general_course": [],
"id": 3,
"name": "College of Education",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1921"
},
{
"colleges": [],
"department": [
13,
17,
19
],
"general_course": [],
"id": 4,
"name": "College of Engineering and Computer Science",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1922"
},
{
"colleges": [],
"department": [
20,
26,
27
],
"general_course": [],
"id": 5,
"name": "College of Health and Human Development",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1923"
},
{
"colleges": [],
"department": [
28,
29,
32,
48
],
"general_course": [],
"id": 6,
"name": "College of Humanities and Social Sciences",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1924"
},
{
"colleges": [],
"department": [
52,
57
],
"general_course": [],
"id": 7,
"name": "College of Natural Sciences and Mathematics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1925"
},
{
"colleges": [],
"department": [
58,
59,
63
],
"general_course": [],
"id": 8,
"name": "Mihaylo College of Business and Economics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1926"
}
]
}
Step 1 - Parsing it into nodejs:
let colleges = JSON.parse(data)
Step 2 - Saving it into the dialogflow app data:
app.data.collegeData = data;
Step 3 - Accessing the length:
let collegeLength = Object.keys(app.data.collegeData.college).length;
Getting following error in firebase console:
TypeError: Cannot convert undefined or null to object
Update:
Here is the code:
if ( app.data.collegeData === undefined ){
app.data.collegeData = [];
}
**Step 1 =>**
showColleges(college);
**Step 2 =>**
function showColleges(collegeName){
if (app.data.collegeData.length === 0){
getCollegeData().then(buildSingleCollegeResponse(collegeName))
.catch(function (err){
console.log('No college data')
console.log(err)
});
}
else{
buildSingleCollegeResponse(collegeName);
}
}
**Step 3 =>**
function getCollegeData(){
console.log('Inside get College Data')
return requestAPI(URL)
.then(function (data) {
let colleges = JSON.parse(data)
if (colleges.hasOwnProperty('college')){
saveData(colleges)
}
return null;
})
.catch(function (err) {
console.log('No college data')
console.log(err)
});
}
**Step 4 =>**
function saveData(data){
app.data.collegeData = data;
console.log(app.data.collegeData)
}
**Step 5 =>**
function buildSingleCollegeResponse(collegeName){
let responseToUser, text;
//console.log('Data is -> '+ Object.keys(app.data.collegeData.college).length);
//console.log('Length is -> '+ app.data.collegeData.college.length);
console.log('Count is -> '+app.data.collegeCount);
let collegeLength = Object.keys(app.data.collegeData.college).length;
if ( collegeLength === 0){
responseToUser = 'No colleges available at this time';
text = 'No colleges available at this time';
}
else if ( app.data.collegeCount < collegeLength ){
for ( var i = 1; i <= collegeLength; i++)
{
console.log('All Colleges:: '+app.data.collegeData.college[i])
let coll = app.data.collegeData.college[i]
let name = coll.name
console.log('checkCollegeExist => College Name:: '+ name)
console.log('checkCollegeExist => Parameter => College Name:: '+collegeName)
if(String(name).valueOf() === String(collegeName).valueOf()){
responseToUser = 'Yes! CSUF has '+collegeName;
text = 'Yes! CSUF has '+collegeName;
}else{
responseToUser = 'CSUF does not teach ' +collegeName+' currently';
text = 'CSUF does not teach ' +collegeName+' currently';
}
}
}
else{
responseToUser = 'No more colleges';
}
if (requestSource === googleAssistantRequest) {
sendGoogleResponse(responseToUser);
} else {
sendResponse(text);
}
}
This is the culprit:
getCollegeData().then(buildSingleCollegeResponse(collegeName))
That calls buildSingleCollegeResponse(collegeName) and then passes its return value into then, just like foo(bar()) calls bar and passes its return value into foo.
You wanted to pass a functon to then:
getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note that now that it's clear from the updated question that app.data.collegeData.college is an array, there's no need for Object.keys. Change:
let collegeLength = Object.keys(app.data.collegeData.college).length;
to simply
let collegeLength = app.data.collegeData.college.length;
Arrays have a length property (whereas non-array objects don't, by default).
You haven't mentioned what value app.data holds before issuing app.data.collegeData = data;
If app.data is undefined you should try app.data = {collegeData: data}
Or else negating what app stores. Following works
app = {};
app.data = {};
app.data.collegeData = data;
app.data.collegeData.college.length
You don't need to do the following
let collegeLength = Object.keys(app.data.collegeData.college).length;
Update: Refer to https://jsfiddle.net/dmxuum79/3/

Firefox gives "301 Moved permanently" error on Http Request

I am currently developping an Angular 4 chat application, which make severals HTTP request.
On Google Chrome or Opera browser, all requests work fine but when I test my app on Firefox, one of them doesn't pass. I have already cleared my cache many times but the problem persists.
this.chatWebService.getLatestConversations(params).subscribe(
(response: CustomHttpResponse<ConversationModel[]>) => {
this.chatSharedService.setDiscussionList(response.data);
},
(errorResponse: HttpErrorResponse) => {
console.log(errorResponse)
});
And the request:
public getLatestConversations(p: { filter: string, search: string, page_index: number, page_count: number }): Observable<{}> {
const url = `${this.messagesUrl}?filter=${p.filter}&search=${p.search}&page_index=${p.page_index}&page_count=${p.page_count}`;
return this.http.get(url, { params: this.createHttpParams(p) });
}
private createHttpParams(params: {}): HttpParams {
const searchParams = new HttpParams();
const keys = Object.keys(params);
keys.forEach(key => searchParams.append(key, String(params[key])));
return searchParams;
}
On Firefox, this code gives me this error:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
Here is a sample of the returned JSON data:
{
"data": [
{
"type": "user",
"id": 76,
"name": "User 1",
"slug": "razx6k5nuser",
"muted": false,
"messages": [
{
"content": "Hi there",
"media": false,
"sent": 1516372902,
"read": true,
"sender": {
"id": 76,
"slug": "razx6k5nuser",
"lastname": "User lastname",
"firstname": "User first name",
"phoneNumber": ""
}
}
]
},
{
"type": "user",
"id": 71,
"name": "User 2",
"slug": "volc6p1suser",
"muted": false,
"messages": [
{
"content": "new message",
"media": false,
"sent": 1516358686,
"read": false,
"sender": {
"id": 77,
"slug": "razv6i2auser",
"lastname": "User lastname",
"firstname": "User first name",
"phoneNumber": ""
}
}
]
}
],
"meta": {
"page": "1",
"total": 18,
"totalNotRead": 1,
"totalMuted": 0
}
}
According to some errors I found on Google, it seems be solved by adding some headers for each request, so I have already added some headers on each of request with the interceptor, like this:
const request = req.clone({
setHeaders: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
But it still doesn't work. Can someone help me? Thank you in advance.

access value in array from Json response typesciprt

How can i access subjects in Json response and take the value which in types using typescript ?
Json Response :
{
"$id": "1",
"Council_ID": 102,
"place": "bla bla bla",
"number": "4644",
"type": 2,
"user_Id": 15,
"subjects": [
{
"$id": "2",
"subjectCode": "464",
"type": 1,
"branch": "cairo",
"gender": true
},
{
"$id": "3",
"subjectCode": "466",
"type": 5,
"branch": "alex",
"gender": true
}
],
"absence": []
}
meeting.component.ts :
this.dataStorageService.getCouncilId(this.meetingID).subscribe(response => {
this.subjectsWithID = response.json();
console.log(this.subjectsWithID, 'All Response')
this.typee = this.subjectsWithID.subjects.type;
console.log(this.typee, 'bla bla');
});
Here is how to access the values
this.subjectsWithID.Council_ID; // 102
this.subjectsWithID.type; // 2
this.subjectsWithID.$id; // '1'
this.subjectsWithID.subjects[0].$id; // '2'
this.subjectsWithID.subjects[0].type; // 1
this.subjectsWithID.subjects[1].$id; // '3'
this.subjectsWithID.subjects[1].type; // 5
I might have misunderstood your question. If so please provide some example of the desired output.
this.dataStorageService
.getCouncilId(this.meetingID)
.map(json)
.map(response => response.subjects.map(subject => subject.type))
.subscribe(response => { ... });

Serialize the response from backend to store ember store

My response from backend is not in form which ember store. I am not able to serialize the response.
response.json
[{
"pk": 127,
"url": "http://example.com/api/galleries/127/",
"gallery_name": "Faces",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
"time": "1 month ago",
"description": "Created by user",
"is_following": true,
"feedPhotos": [{
"pk": 624,
"url": "http://example.com/api/photos/624/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
"comments_url": "http://example.com/api/photos/624/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
"fivers_pk": 1362,
"fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
"fullphoto_pk": 1362,
"is_fived": true,
"hiFiveKarma": 1,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 574,
"url": "http://example.com/api/photos/574/",
"profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
"userName": "Rohini",
"userKarma": 194,
"caption": "Life # Myanmar!",
"numComments": 0,
"owner": "http://example.com/api/users/45/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
"comments_url": "http://example.com/api/photos/574/comments/",
"numFives": 2,
"fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
"fivers_pk": 1303,
"fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
"fullphoto_pk": 1303,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 45,
"userFirstName": "Rohini",
"is_bookmarked": false
}
]
}, {
"pk": 65,
"url": "http://example.com/api/galleries/65/",
"gallery_name": "Royal",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
"time": "2 months ago",
"description": "This is a gallery about Royal",
"is_following": false,
"feedPhotos": [{
"pk": 347,
"url": "http://example.com/api/photos/347/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
"comments_url": "http://example.com/api/photos/347/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/759/fivers/",
"fivers_pk": 759,
"fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
"fullphoto_pk": 759,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 593,
"url": "http://example.com/api/photos/593/",
"profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
"userName": "Vikanshu",
"userKarma": 932,
"caption": "Marvelous architecture!! in Florence, Italy",
"numComments": 0,
"owner": "http://example.com/api/users/48/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
"comments_url": "http://example.com/api/photos/593/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
"fivers_pk": 1363,
"fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
"fullphoto_pk": 1363,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 48,
"userFirstName": "Vikanshu",
"is_bookmarked": false
}]
}]
How do I serialize this using JSONPISerailizer or any other serializer in ember-cli so that it gets stored in ember store
Reference jsonapi.org
++++Top Level:
Root:
A JSON object must be root of every JSON API request response.
A document must contain at least one top-level members:
1. data: documents "primary data"
2. errors: an array of error objects (id,status,code,title....)
3. meta: a meta object that contains non-standard meta-information (copyright,author...)
member data and errors must not co-exist together.
"data"{}
+++++Resource Objects
1. A resource object MUST contain atleast following top-level member
*id
*type
```
//structure-1
//for galleries
{
"data": {
"type": "galleries",
"id": "1"
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1"
}
}
```
In addition, a resource object may contain any of these top-level members
*attributes
*relationship
*links
*meta
//added attributes first
```
//structure-2
//for galleries
{
"data": {
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
}
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}
}
```
//Adding relationship
Relationship object must contain atleast one of the following
*links (containing atleast one of "self" or "related" resource link
*data
*meta
//link in relationship (minimum one required from link,data,meta).
//
```
//structure-3
//for galleries
{
"data":[{ //Array(square bracket as adding relationship one more item to data
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
}]
}
}
```
//data in relationship
```
//structure-4
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}]
}
}
```
//Adding related resource "included"
```
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},
{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
```
For collections. I am not confident but try this
Now for collection of galleries.
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
},{
"type": "galleries",
"id": "2",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "79"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "79",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
============Implementation part =================================
JSONSerializer normalization process follows these steps
*normalizeResponse : entry method.
*normalizeCreateRecordResponse : a normalizeResponse for specific operation.
*normalizeSingleResponse|normalizeArrayResponse:
- for methods like createRecord. we expect a single record back.
- for methods like findAll we expect multiple records back.
+normalize =
normalizeArray iterates and calls normalize for each of it's records
normalizeSingle call its once.
+extractID | extractAttributes | extractRelationships
= normalize delegates to these method to turn record payload into jsonAPI format
Starting with normalizeResponse method. If you open and see normalizeResponse method
in json-serializer
link normalizeResponse: https://github.com/emberjs/data/blob/v2.2.1/packages/ember-
data/lib/serializers/json-serializer.js#L192
you with find a switch case switch(requestType). If requestType if
"findRecord" then "normalizeFindRecordResponse" is called
"queryRecord" then "normalizeQueryRecordResponse" is called
"findAll" then "normalizeFindAllResponse" is called
...so on and so forth.
if you notice the parameter passed to all the methods are same as that of normalize
(...arguments) :)
**Lets start for findAll
i.e normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse
as normalizeFindAllResponse method has only one line that call
normalizeArrayResponse.
normalizeFindAllResponse
normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse ->
_normalizeResponse{ extractMeta,normalize }
extractMeta [extract meta information like pagination and stuff ]
if single: normalize []
example of normalize method in emberjs docs
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
"normalizeArrayResponse calls `return this._normalizeResponse
(store,primaryModelClass,payload,id,requestType,false).
so isSingle is false for _normalizeResponse method. so we will have to push all the
related records of included array
in our case the photos which is done by below snippet from "_normalizeRespose"
method.
_normalizeResponse
```
else{
documentHash.data = payload.map((item) => {
let { data, included } = this.normalize(primaryModelClass,item);
if(included){
documentHash.included.push(...included);
}
return data;
});
return documentHash;
}
```
Things are still unclear in the context of our JSON reponse from server
but atleast we know the flow now.
Lets try to apply it for findAll ( as per the flow above).
run "ember g serializer application" //assuming you are using ember-cli and you
intend to make this serializer generic for application.
As of now I have no information how and when normalizeResponse is called. :(
I just scanned through and guess on recieving data from server the store calls
normalizeResponseHelpers which in turn calls normalizeResponse.
In any case "normalizeResponse" is going to send payload and other necessar
information to normalizeFindAllResponse(...arguments) which in turn will call
normalizeArrayResponse(...arguments) which in turn will call "_normalizeRespone".
Here is where we need to take action
for extraMeta and normalize.
+extraMeta
I am not sure if there is any meta information in you json response.
in case there is you can refer to the example mentioned in docs
extractMeta
So I guess you can directly user the normalize method from example in your application ;).
please try and check. Since i am learning ember myself I cannot guarantee it will work but it should. the lonngggg explation is my thought while i was learning the problem/solution
//app/serializers/application.js
+normalize
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
The primary key in the JSON from server is pk. You will have to mention that too
http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: 'pk'
});

Error getting JSON Map<String, Object> with SpringMVC and Jackson2

I'm trying to get a Map where there are a 'number' with the number of actions and 'actions' with a list of actions.
I've checked the list of actions in java and it works just fine.
I have 4 actions and in json file I'm getting right just the first one.
Controller in java
#RequestMapping(value = "/getactions/{idTask}", method = RequestMethod.GET, produces = "application/json")
#ResponseBody
public Map<String, Object> getActions(Principal principal,
#PathVariable Long idTask) {
logger.info("Task controller get actions...");
List<TaskAction> actions = null;
if (principal == null) {
actions = new ArrayList<TaskAction>();
} else {
actions = taskActionService.getAllTaskActions(idTask);
}
System.out.println(">>>>>>>>Task Controller - Actions>>>>>>>>>>>>> "
+ actions.size());
for (TaskAction ta : actions) {
System.out.println(">>>>>>>>ta: " + ta.getActionname());
}
System.out.println(">>>>>>>>END getAllActions()>>>>>>>>>>>>> ");
Map<String, Object> data = new HashMap<String, Object>();
data.put("actions", actions);
data.put("number", actions.size());
return data;
}
Sysout
>>>>>>>>Task Controller - Actions>>>>>>>>>>>>> 4
>>>>>>>>ta: tacometer
>>>>>>>>ta: hola
>>>>>>>>ta: hi there
>>>>>>>>ta: other action
>>>>>>>>END getAllActions()>>>>>>>>>>>>>
I'm not getting any error, but the json result only gets the first element in the action list and the id of the rest of actions.
json that I get from http...getactions/8
{
"number":4,
"actions":[
{ ... },
3,
4,
5
]
}
The ... is the first action that is well recovered. (I've avoided to write the code for clearity)
Any ideas about what could it be?
Thanks in advance.
Example of json with 2 actions
{
"number": 2,
"actions": [{
"idTaskAction": 4,
"task": {
"idTask": 8,
"taskname": "abbbbbbbbbbbbbb",
"description": "fffffffffffffffqqqqq",
"date": 1389569940000,
"deadline": -23918633280000,
"category": {
"idTaskCategory": 1,
"sortOrder": 0,
"categoryname": "cat1",
"timestamp": 1402437394000
},
"priority": {
"idTaskPriority": 1,
"sortOrder": 0,
"aka": "none",
"priorityname": "low",
"timestamp": 1402437527000
},
"state": {
"idTaskState": 1,
"statename": "pending"
},
"user": {
"idUser": 1,
"username": "joe"
},
"userResponsible": {
"idUser": 1,
"username": "joe"
},
"evaluation": "12345678saad",
"pending": 0,
"actions": [{
"idTaskAction": 2,
"task": 8,
"date": 1402652358000,
"actionname": "tacometer",
"description": "asfdafa",
"duration": 12,
"user": {
"idUser": 1,
"username": "joe"
},
"timestamp": 1411493866000
},
{
"idTaskAction": 3,
"task": 8,
"date": 1404207558000,
"actionname": "hola",
"description": "un dos tres",
"duration": 20,
"user": {
"idUser": 1,
"username": "joe"
},
"timestamp": 1405022827000
},
4,
{
"idTaskAction": 5,
"task": 8,
"date": 1412164741000,
"actionname": "other action",
"description": "ya me my",
"duration": 22,
"user": {
"idUser": 1,
"username": "joe"
},
"timestamp": 1411733131000
}],
"timestamp": 1411733131000
},
"date": 1412074440000,
"actionname": "hi there",
"description": "lkjñlkj ya",
"duration": 25,
"user": {
"idUser": 1,
"username": "joe"
},
"timestamp": 1411733090000
},
5]
}
The problem was that the classes Task, User... has #JsonIdentityInfo with ObjectIdGenerator.PropertyGenerator.class option so when Jackson try to serialize the object into json, if the object it is already in the file, then it is not added again. This way avoid to serialize json file with infinite recursions.
To solve this we need to change ObjectIdGenerator.PropertyGenerator.class for ObjectIdGenerator.None.class so that the objects are serialized even if they are already part of other objects.
Change
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "#id")
for
#JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "#id")