Reputation: 833
I have a form where a user can have multiple addresses. An address contains for example of a street and country to keep things simple.
What I have is the following in my view. Whenever a user presses the button, a different div with input pops up, which works good.
<div ng-repeat="address in addresses">
<input type="text" ng-model="address.streetname" placeholder="streetname"/>
<input type="text" ng-model="address.country" placeholder="country"/>
</div>
<button class="button" ng-click="addNewAddress()">Add address</button>
Part of my AngularJS controller:
var formData = {
//...
"addresses" : $scope.addresses
};
Spring Controller:
String[] addresses = request.getParameterValues("addresses");
for(String address : addresses) {
System.out.println(address); //ACTUALLY PRINTS SOMETHING
JSONObject j = new JSONObject(address); //ouch error.
System.out.println(j.toString());
}
The following gets printed in my spring console (I have only filled in the streetname with values 'aaa', 'bbb', 'ccc'.
[{"address":"","$$hashKey":"object:4","streetname":"aaa"},{"address":"","$$hashKey":"object:6","streetname":"bbb"},{"address":"","$$hashKey":"object:8","streetname":"ccc"}]
The error message:
A JSONObject text must begin with '{' at 1 [character 2 line 1]
Edit: Now it is working thanks to the two below, I just have to point out that there is no need to use request.getParameterValues(). Instead, just use request.getParameter("valuehere") and directly parse it to a jsonarray.
Upvotes: 0
Views: 422
Reputation: 2465
Your error is from JSONObject serialization not Spring's since you are not using @RequestBody
(you might take a look here). Your json is an array which you are trying to convert into an object objects are the things between { }
, thats why it's given you exception, you need a JSONArray instead
String[] addresses = request.getParameterValues("addresses");
for(String address : addresses) {
System.out.println(address);
JSONArray jArray = new JSONArray(address); //here!
System.out.println(jArray.toString());
//interate over array (like any other array) and do stuff, get the objects etc..
}
Or just change you array into an object with Angular
Upvotes: 1