I am trying to pass an array collection from flex page to my backend java.Here is the code,
private function getItems():void{
myObj = new Object();
myObj['dId']= dId.value.toString();
myObj['itmList']=JSON.encode(itmList);// trying to pass like this..
var url:String = URLManager.baseURL;
url = url+"myController/ReportController?do=getItems";
url = url+"¶meter="+ escape(JSON.encode(myObj))
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest,"_blank");
}
My itmList is an array collection, how can I pass it from JSon to Java controller? And how to get that in Java?
JSON.encode the itmList source array instead. (i.e. itmList.source is an array)
Then use HTTPService instead:
HTTPService AsyncToken and AsyncResponder example
Another option is to use JSON.stringify instead (Flash has had native JSON support since FP 11). Just make sure you remove the import com.adobe.serialization.json.JSON; from the top of your file.
myObj['itmList']=JSON.stringify(itmList);
Or, since you're encoding your whole data object,
myObj['itmList']=itmList.source;
var url:String = URLManager.baseURL;
url = url+"myController/ReportController?do=getItems";
url = url+"¶meter="+ escape(JSON.stringify(myObj))
var urlRequest:URLRequest = new URLRequest(url);
navigateToURL(urlRequest,"_blank");
Related
Since Web3J doesn't currently support ERC1155, is there a way to get the balance for a wallet? My guess is to use a function for this, but I can't seem to figure out how to get it to work.
Function function = new Function(
"balancedOf",
Arrays.asList(new Address(ethAddress), new Uint256(1)),
Arrays.asList(new org.web3j.abi.TypeReference<Bool>() {}));
String data = FunctionEncoder.encode(function);
Do I then create a transaction? Or do I use ethSendRawTransaction? balanceOf only has 2 input so I would expect to have to invoke it from a smartcontract, but I don't see a way to do it.
From reading the web3j docs, It seems that you can do the following:
Function function = new Function<>(
"functionName",
Arrays.asList(new Type(value)), // Solidity Types in smart contract functions
Arrays.asList(new TypeReference<Type>() {}, ...));
String encodedFunction = FunctionEncoder.encode(function)
org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
Transaction.createEthCallTransaction(<from>, contractAddress, encodedFunction),
DefaultBlockParameterName.LATEST)
.sendAsync().get();
List<Type> someTypes = FunctionReturnDecoder.decode(
response.getValue(), function.getOutputParameters());
The response object, from org.web3j.protocol.core.methods.response.EthCall does the JSON-RPC call "eth_call" which only retrieves data form the blockchain.
I believe this is the equivalent of doing in web3js the following:
let contract = new web3.eth.Contract(<ABI>, <Contract Address>);
const res = await contract.functionName(<params>);
I have a string that i'd like to stringify in Kotlin (Android), but it seems that org.json.* doesn't support taking a string and re-stringifying it, instead it always tries to parse it first.
val str = "test=\"123\""
val stringified = JSONObject(str).toString() // JSONException: Value a of type java.lang.String cannot be converted to `JSONObject`
The use case for this ability is passing data to JS inside a Webview in a secure manner.
val json = "test=\"123\""
webview.evaluateJavascript("window.onData(${json})")
// on the JS side it will look like this: window.onData(test="123")
// this is both invalid and insecure since it opens the door for raw JS injection
Any attempt to do it manually will result in an insecure and possibly invalid JS string
This example should NOT be used:
val insecureJSON = "'${str.replace("\\", "\\\\").replace("\"", "\\\"").replace("'", "\'")}'"
The desired behavior:
val json = jsonStringifyString("test=\"123\"")
webview.evaluateJavascript("window.onData(${json})")
// rendered JS: window.onData("test=\"123\"")
Is there an easy method for stringifying a string in Android?
Ended up using the JSONArray class and removing the array wrapping to trick the class to stringify a plain string
fun jsonStringifyString(str: String): String {
val jsonStr = JSONArray().put(str).toString()
return jsonStr.substring(1, jsonStr.length - 1) // remove first and last char
}
val serializedData = jsonStringifyString("test=\"123\"");
webview.evaluateJavascript("window.onData(${serializedData})")
// rendered JS: window.onData("test=\"123\"")
I have the following SP (SQL server) that return a Json output.
BEGIN
SET #jsonOutput = (
SELECT
Program.Name AS ProgramName,
ProgramOwner.FirstName AS OwnerFirstName,
FROM ProgramOwner, Program
WHERE Program.Id = ProgramOwner.ProgramOwner2Program
FOR JSON PATH,WITHOUT_ARRAY_WRAPPER)
I would like to map the return Json output to a List of ProgramDto via modelMapper. Not sure hot to do that since the return values from call.execute is an Object.
Something like this:
SimpleJdbcCall call = new
SimpleJdbcCall(jdbcTemplate).withProcedureName(programProc).declareParameters(
new SqlOutParameter("jsonOutput", Types.VARCHAR));
Map<String,Object>out = call.execute(new MapSqlParameterSource());
if(out.size()>0) {
// Only to show what I am trying to do
Type rootType = new TypeToken<List<ProgramDto>>() {}.getType();
modelMapper.map(out.get("jsonOutput"),rootType );
}
Thank you
As I understood you are trying to get a list of object from
You can use Jackson api
Like this
say for example your json is in variable named jsonData, then you can get the object you need like below.
ObjectMapper mapper = new ObjectMapper();
List<Type> myList = Arrays.asList(mapper.readValue(jsonData, Type[].class));
You can also find more examples here
I'm trying send information from a FreeMarker template to my Java model class.
I've tried this:
//my array of string casted in a string
var pais = selected.join();
request.setAttribute(pais, "paises");
Ok, now I'm trying collect this content in my Java class doing this:
String paises = MgnlContext.getAttribute("paises");
But it doenst work. I tried other methods like this:
Stirng paises = MgnlContext.getInstance().getAttribute("paises");
But it always returns null.
SOLUTION (sending info by ajax):
first get the values by javscript :
[#assign cpathx = ctx.contextPath]
[#assign url = model.getUrl() /]
var field = $('#key').val();
var calin = $('#calendarIni').val();
var calfin = $('#calendarFin').val();
var pais = selected.join();
var url = '${cpathx}${url}?paises='+pais+'&palabra='+field+'&calendarini='+calin+'&calendarfin='+calfin;
jQuery.post(url ,function(data) {
jQuery('#ajax').html(data);
});
Now we can collect the info in java:
String paises = MgnlContext.getWebContext().getAttribute("paises");
String queryString = MgnlContext.getWebContext().getAttribute("palabra");
String dateStart = MgnlContext.getWebContext().getAttribute("calendarini");
String dateEnd = MgnlContext.getWebContext().getAttribute("calendarfin");
That first piece doesn't look like freemarker but more as JavaScript, so maybe that is your problem. While freemarker directives are executed server side, html and Js produced by freemarker is executed client side so w/o Ajax call there's no way for Js to talk back to server (and thus to model class).
If you were really interested in passing something from freemarker to java model, model is exposed directly. You can simply add method in java model and call it from freemarker template like
${model.myMethod(someParam)}
HTH,
Jan
I need to pass waypoints to google maps javascript directions api from ManagedBean to jsf page.
I'm trying to make JSONArray and pass it to jsf:
private JSONArray routesJSON;
with getters and setters.
Than im creating JSON : in loop im adding Strings with LatLang of waypoints to List<String>
routes.add("new google.maps.LatLng(" + o.getLatitude() + "," + o.getLongitude()+")");
And im getting JSON :
[{"location":"new google.maps.LatLng(50.495121,22.1705)"},{"location":"new google.maps.LatLng(50.57082,22.06813)"},{"location":"new google.maps.LatLng(50.570549,22.047871)"},{"location":"new google.maps.LatLng(50.521389,21.912695)"},{"location":"new google.maps.LatLng(50.495121,22.1705)"}]
from:
for()
array.put(obj);
}
System.out.println(array);
in JSF function for displaying route : (it works with hardcoded data)
function calcRoute() {
var waypts = [];
var start = new google.maps.LatLng(#{someBean.startLatitude}, #{someBean.startLongitude});
var end = new google.maps.LatLng(49.712112, 21.50667);
var way = #{someBean.routesJSON};
var request = {
origin:start,
destination:end,
optimizeWaypoints: true,
waypoints:way;
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
But when im displaying that page map doesnt appear. I know it's probably because of " in JSON but i dont know how to remove it. Or may there are easiest ways to pass waypoint data from Bean to jsf page?
Instead of returning a JSON data packet that contains javascript statements like "new google.maps.LatLng(50.495121,22.1705)", it's more sensible to return just the coordinates.
So if you had a JSON packet that looks like this in your javascript (I don't know how to pass data between your Java and Javascript):
var routes = [
{"lat":"50.495121", "lng":"22.1705"},
{"lat":"50.57082", "lng":"22.06813"},
{"lat":"50.570549", "lng":"22.047871"},
{"lat":"50.521389", "lng":"21.912695"},
{"lat":"50.495121", "lng":"22.1705"}
]
You can turn this into an array like so:
var way = [];
for (var i = 0; i < routes.length; i++) {
way.push(new google.maps.LatLng(parseFloat(routes[i].lat), parseFloat(routes[i].lng)));
}
NB: the use of parseFloat to convert strings like "50.495121" into floating point numbers.