Reputation: 567
I have a json object in javascript,
filters = Object {assetType: "CAR~LIGHT TRUCK", bodyType: "SEDAN~SPORT UTIL"}
I need to pass these values along with 5 more string value in query string.
url = '/starHome/exportToCsv/'+tier+'/?period='+period+'&level2='+level2+'&level3='+level3+'&level4='+level4+'&filters='+filters;
window.location.href = url;
when I tried to get filter parameter value in controller
request.getparamter("filters");
I get "[object object]
"
how can I pass this value to controller?. I have a pojo class contains all these fields. Can I make use of that class?.
Upvotes: 1
Views: 39485
Reputation: 4473
Another alternative is to use the encodeURI and decodeURI functions. First, we encode the JSON string so that it won't cause any issues in the URL. When we get the value back, we decode the string and then parse its JSON.
In this approach, the content is human readable and parsable at the backend without too much effort.
const values = {prices:[1,2,3], sale: true, minAmount: 500 };
const json = encodeURI(JSON.stringify(values));
const result = JSON.parse(decodeURI(json));
Upvotes: 1
Reputation: 3527
I found the following as the best solution so far using Javasript
var a = {a:'foo',b:[1,2,3],g: {q:"8798"}};
var b = window.btoa(JSON.stringify(a));
console.log(b) // output eyJhIjoiZm9vIiwiYiI6WzEsMiwzXSwiZyI6eyJxIjoiODc5OCJ9fQ
// restore b again
console.log(JSON.parse(window.atob(b))); // output : {a:'foo',b:[1,2,3],g: {q:"8798"}}
Upvotes: 8
Reputation: 567
Thanks Everyone,
I have used JSON.stringify(filters);
and in controller
String filtersString = request.getParameter("filters");
Map<String,Object> result = new ObjectMapper().readValue(filtersString, HashMap.class);
Kindly reply back, if there s a better approach.
Upvotes: -1
Reputation: 339
You might be able to use jQuery.param()
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
var filters = {assetType: "CAR~LIGHT TRUCK", bodyType: "SEDAN~SPORT UTIL"};
filters = jQuery.param( filters );
console.log("filters ", filters );
//filters assetType=CAR~LIGHT+TRUCK&bodyType=SEDAN~SPORT+UTIL
url = '/starHome/exportToCsv/'+tier+'/?period='+period+'&level2='+level2+'&level3='+level3+'&level4='+level4+'&filters='+filters;
</script>
Upvotes: 1
Reputation: 2968
You can encode your json string in base64 and then use it in the url:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa
Upvotes: 4