Jpatel Jpatel - 1 month ago 26
AngularJS Question

How to send multiple objects from Angular2 to Java Spring backend

I am trying to send two objects (

CustomerAcct
and
Product
) from Angular 2 to restful services (Java Spring). I am using a wrapper object called
CustProduct
, which has two objects in it,
CustomerAcct
and Product. Somehow on the back end
CustomerAcct
object is null but Product object is not.

Here is my code:

GUI:

CustProduct class:

export class CustProduct { public ca: CustomerAcct; public prod: Product }


Service:

addProductToCustomer(cp: CustProduct): Observable<Boolean> {

let body = JSON.stringify(cp);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
let url = 'my-url';

return this.http.post(my-url, body, options)
.map(this.extractData)
.catch(this.hadnleError);
}


Backend code:

java classes:
@Entity
@Table(name="CUSTOMER_ACCT")
public class CustomerAcct {
@Id
@Column(name="CUSTOMER_ACCT_ID")
private long CUSTOMER_ACCT_ID;
@Column (name="CUSTOMER_NAME")
private long CUSTOMER_NAME;

other additional fields
}

@Entity
@Table(name="PRODUCT")
public class Product {
@Id
@Column(name="PRODUCT_ID")
private long PRODUCT_ID;
@Column(name="PROD_DESC")
private String PROD_DESC;

other additional fields
}

public class CustomerProduct {
CustomerAcct customerAcct;
Product product;
}

public boolean addProductToCustomer(@RequestBody CustomerProduct cp) {
CustomerAcct ca = cp.customerAcct;
Product prod = cp.product;

// Here CustomerAcct is null, but I do see data in Product object
}


I don't understand why it is dropping
CustomerAcct
object. If I send
CustomerAcct
object in
@RequestBody
by itself, it works but not in the wrapper object. My class definitions on GUI and backend are same.

Thanks for you help.

Answer

You're using a simple JSON conversion, which means that in the JSON object your keys are ca and prod. By default, Jackson expects the keys to match the field names, which are customerAcct and product. The simplest approach is probably to annotate your Java fields with @JsonField("ca"). (Alternately, you could rename the properties in either Java or JavaScript.)