I have got a HTTP request in my Swift code that sends a POST request to my PHP code.Here is my php code
class Comment
{
public $CommenterName;
public $CommentDate;
public $CommentLikes;
function __construct($CommenterName,$CommentDate,$CommentLikes)
{
$this->CommenterName = $CommenterName;
$this->CommentDate = $CommentDate;
$this->CommentLikes = $CommentLikes;
}
}
And my php codes returns an array full of Comment objects.Now when i receive this in swift i do something like this
let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
print(jsonData[0])
Printing this returns me
{
CommentDate = "2017-06-29 01:21:57";
CommentLikes = 2;
CommenterName = muradsh;
}
And when i want to access one of this objects like this
print(jsonData[0][2])
or this
print(jsonData[0]["CommenterName"])
it returns me this following error Type 'Any' has no subscript members.
How can i get access to CommenterName in jsonData?
Since the data you get is really an array of objects try casting it like this:
let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
Related
I have existing PHP that accepts arrays as parameters. This is currently being invoked from javascript and the javascript array is being set directly as part of the data object sent through AJAX call to the php.
Now, I want to send an array from an Android app and I don't want to change the existing php and javascript. I have looked for an answer, but don't see anything, other than the suggestion to encode the array as JSON and decode it in the php, but that will require lots of changes everywhere, including the javascript. It appears the javascript and the php are made to just work. Maybe something is done automatically to the array?
The PHP looks like this:
foreach($_POST as $key => $value) {
if (is_array($_POST[$key])){
for ($index = 0; $index < count($_POST[$key]); $index++){
if(ini_get('magic_quotes_gpc'))
$_POST[$key][$index] = stripslashes($_POST[$key][$index]);
$_POST[$key][$index] = htmlspecialchars(strip_tags($_POST[$key][$index]));
}
}
else {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
}
So, it is definitely expecting some parameters to be arrays.
The javascript currently does this:
$.ajax({
type: "POST",
url: 'php/getLibraryPatterns.php',
dataType: 'json',
data: data,
and data is a javascript object with arrays contained in it. For example:
var data = {};
if (sortBy.length > 0){
data.sortBy = sortBy;
}
and sortBy is an array in the javascript.
How do I pass an array from the Android app to this php? Currently, all of the parameters for my other calls to php have just been simple strings, so I use the following function to put all the parameters together in a string and then write that to the OutputStream of my HttpURLConnection. I have that all working, just not sure what to do with the arrays?
private String buildParameterString() throws UnsupportedEncodingException
{
if (m_parameterMap == null) return "";
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<Map.Entry<String, String>> itr = m_parameterMap.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<String, String> param = itr.next();
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(param.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(param.getValue(), "UTF-8"));
}
return result.toString();
}
I tried creating a JSONArray with the data, then convert to string and set it just like I would set the other strings I am sending. But, this does not appear to work, at least not automagically.
So, I am sending something like "[29]" or "['sortAsc']" as strings in the parameters.
I got back an empty list. I will continue to debug in the php to see what those look like there, but I expect they will be just strings and the php won't know what to do with that.
So, how can I send an array to the php? I don't want to have to change the php, as that means that the javascript then also has to change. Is there any way to do this from a java Android app?
Solution Found!
I found an answer in the JQuery documentation for ajax method. It says there that arrays are encoded like this:
%5B is '['
and %5D is ']'
For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.
I have encoded my arrays like that in the string that I write to the output stream. From https://api.jquery.com/jQuery.ajax/
Here is the code I am using to create my output stream:
private String buildParameterString() throws UnsupportedEncodingException
{
if (m_parameterMap == null || m_parameterMap.size() == 0) return "";
StringBuilder result = new StringBuilder();
for (int iPair = 0; iPair < m_parameterMap.size(); iPair++)
{
Pair<String, Object> param = m_parameterMap.get(iPair);
if (iPair > 0) result.append("&");
Object value = param.second;
if (value instanceof ArrayList){
for (int i = 0; i < ((ArrayList)value).size(); i++){
Object nextValue = ((ArrayList)value).get(i);
String nextValueStr = "";
if (nextValue instanceof String){
nextValueStr = (String)nextValue;
}
else {
nextValueStr = Integer.toString((Integer)nextValue);
}
if (i > 0) result.append("&");
result.append(URLEncoder.encode(param.first, "UTF-8"));
result.append("%5B%5D=");
result.append(URLEncoder.encode(nextValueStr, "UTF-8"));
}
}
else {
result.append(URLEncoder.encode(param.first, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode((String)value, "UTF-8"));
}
}
return result.toString();
}
m_parameters is an ArrayList of Pair's where Pair is in android.util.
It works, this is the answer. You don't have to encode and decode in JSON string to do this. All the othere answers I have seen for this are just that. There is a way to encode the array into the string output.
Try this:
Outside of while loop:
JSONArray data = new JSONArray();
And put this in while loop:
JSONObject jsonObjSend = new JSONObject();
jsonObjSend.put(param.getKey(), param.getValue());
data.put(jsonObjSend);
From Android, send it as json data
public String convertMapToJson() {
Map<String, String> elements = new HashMap<>();
elements.put("Key1", "Value1");
elements.put("Key2", "Value2");
elements.put("Key3", "Value3");
JSONObject json = new JSONObject(elements);
return json.toString();
}
In server side PHP,
$json = file_get_contents('php://input');
// Converts it into a PHP object
$params = json_decode($json, true);
echo $params["Key1"];
I am trying to fetch some data from server using json in my flutter app. This is the function I am using.
List<String> userFriendList = ["No Friends"];
Future<http.Response> _fetchSampleData() {
return http.get('//link/to/server/fetcher/test_fetcher.php');
}
Future<void> getDataFromServer() async {
final response = await _fetchSampleData();
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
userLvl = data["lvl"].toString();
userName = data["name"];
userFriendList = List();
userFriendList = data["friendlist"];
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print('Failed to load data from server');
}
}
I get the usrLvl and userName right. But for userFriendList, I get the following error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>'
Code on the server end (test_fetcher.php) :
<?php
$myObj->name = "JohnDoe";
$myObj->lvl = 24;
$friends = array("KumarVishant", "DadaMuni", "BabuBhatt", "BesuraGayak", "BabluKaneria", "MorrisAbhishek", "GoodLuckBaba", "ViratKohli", "LeanderPaes");
$myObj->friendlist = $friends;
header('Content-Type: application/json');
$myJSON = json_encode($myObj);
echo $myJSON;
?>
This is a cast error: List<dynamic> != List<String>
You can convert / cast your list in several ways.
I advise you to use this library to simplify your json / Dart object conversion
: https://pub.dev/packages/json_serializable
json_serializable will generate the conversion methods (fromJson and toJson) and take care of everything.
It's easier and safer than doing it manually.
Just what the error says. The userFriendList is of type List you have it as List.
List<String> userFriendList = ["No Friends"];
Should be
List<dynamic> userFriendList = [];
Or a different list entirely if this doesn't work for you.
The error explains it. The fetched data from the server api is decoded to type List<dynamic> and you declared userFriendList to be of type List<String>. What you need to do is change the type of userFriendList from
List<String> userFriendList = ["No Friends"];
to:
List<dynamic> userFriendList = [];
I want to test my API function by sending array of objects via postman
When I send my request in JSON format to the function and then looping through the array to access each object property it gives me the following error:
https://i.imgur.com/QV9MDsm.jpg
Here is my request:
https://i.imgur.com/4584wf3.jpg
I searched how to send an array of objects using postman and found that I am doing it the right way
I selected row under body section so I can add my request body and selected it's format as JSON and added "Content-Type: application/json" to the request header
My API function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine->machineNo;
$newMachine->account_type = $machine->accountType;
$newMachine->machine_type = $machine->machineType;
$newMachine->retialer_id = $retailer->retailerId;
$newMachine->save();
}
}
I expect that i can access each array object properties as a PHP object but I found that it is not an object by testing it using is_object() function:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
return response()->json(is_object($machine));
}
}
I do not know if the problem is within my request or something that I might misunderstand while retrieving data of the request in my controller function
Either it is an array and in that case, you can call
$object = (object) $machine;
Or it is a string aka JSON, you can call
$object = json_decode($machine);
Or if it is an object/array use
$machine['machineType'];
Also please add a dump of the $machine var
EDIT
Try sending the request not using [] because they will be converted into an array with objects in it, instead, if you remove the [] and only have {} it should only be one object in the request
"machineInfo" : {
"machineNo" : "1123213",
"accountType" : "Paid",
//...rest here..
}
Try this:
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$object = (object) $machine;
return response()->json(is_object($object));
}
}
Since your request sends data as an array, you can access the elements as so :
public function createRetailer(Request $request){
$machines = $request->machineInfo;
foreach($machines as $machine){
$newMachine = new Machine;
$newMachine->machine_no = $machine['machineNo'];
$newMachine->account_type = $machine['accountType'];
$newMachine->machine_type = $machine->['machineType'];
$newMachine->retialer_id = $retailer->['retailerId'];
$newMachine->save();
}
}
I am trying to communicate to a php server from my gwt project.
I already got a GET request to work, however, my POST request doesn't work so far.
Here's my code:
Button synchronize = new Button("synchronize ",
new ClickHandler() {
public void onClick(ClickEvent event) {
String myurl = URL
.encode("php/test.php");
RequestBuilder builder = new RequestBuilder(
RequestBuilder.POST, myurl);
JSONObject jsonValue = new JSONObject();
jsonValue.put("name", new JSONString("Abc"));
builder.setHeader("Content-Type", "application/json");
try {
Request request = builder.sendRequest(jsonValue.toString(),
new RequestCallback() {
public void onError(Request request,
Throwable exception) {
processResponse("ERROR");
}
public void onResponseReceived(
Request request,
Response response) {
if (200 == response.getStatusCode()) {
processResponse(response
.getText());
} else {
processResponse("ERROR");
}
}
});
} catch (RequestException e) {
processResponse("ERROR");
}
}
});
public void processResponse(String responseString) {
Window.alert(responseString);
}
I can see that the post request goes out and the request payload is a json-object. However, when I try to access the data in the php script, I get the error that the index name is undefined.
Here's the PHP:
<?php
echo $_POST["name"];
?>
Is there something wrong with my PHP?
Does anyone have a working example for this?
While I haven't checked the PHP documentation so far, I tend to remember, that $POST contains the post request's variables, especially useful in a x-www-form-urlencoded request. .. Checked it, yes. I am right :-)
What you actually want is to read the body of the post request and parse it's JSON content to a PHP array or hash.
To read the body see here: How to get body of a POST in php?
$entityBody = file_get_contents('php://input');
Parsing json is described here: Parsing JSON file with PHP
I will not quote the code from there, as it maybe does not exactly fit your needs, but you look for json_decode($json, TRUE).
I have values inside an XMLList in Actionscript. Need to send these values to the DB and update it.
My actionscript code is as follows:
public static function saveUserPermList():void {
var ht:HTTPService = new HTTPService();
ht.url = Config.getServerURL();
ht.method = URLRequestMethod.POST;
//ht.resultFormat = "e4x";
ht.contentType = "text/xml";
ht.request["action"] = "saveUserPermListXML";
ht.request["pdata"] = Application.application.userPermListModel.toString();
ht.addEventListener(ResultEvent.RESULT,AdminUserList.saveUserPermListResult);
ht.send();
}
public static function saveUserPermListResult(e:ResultEvent):void {
trace(e);
}
How can I send the XMLList data to PHP? Should I add a toString() to it?
Also what should be the contentType in Flex.
How can I catch this inside PHP, pl let me know, trying to use, this way,
if($user -> isAllowedAccess()) {
header("Content-type:text/xml");
$postedData = $_POST["pdata"];
// $xmldoc = simplexml_load_string($POST['pdata']);
// echo($xmldoc);
}
No luck. Pl let me know.
The method property of HTTPService should probably be "POST", and the contentType for the request itself should probably be "application/x-www-form-urlencoded".
On the PHP side, $_POST["pdata"] would then be a string containing XML markup. You could either save that in a database directly, or first parse it into XML (via SimpleXML or DOMDocument) and do something with the contained data.
PS: I've just found this answer that seems to shed some light on the internal behavior of the HTTPService class.