Using gson to parse jsonarray and jsonobject - arrays

a login api when success return:
{"status":0,"data":{userid:1,username:"abc"},"msg":"login sucess"}
but when error server return:
{"status":0,"data":[],"msg":"login failure!"}
how to define a object, then use gson to parse the data field!
thanks.

Is it json or gson? For example your response is on this variable $response;
You can try:
<?php
$response = '{"status":0,"data":{userid:1,username:"abc"},"msg":"login sucess"}';
// $response = '{"status":0,"data":[],"msg":"login failure!"}';
$response = json_decode($response);
if(empty($response->data){
echo $response->msg;
}
// print_r($response); //you can try to print_r $response here
// if have data to login, do what you want

Related

how to get property from api body in laravel?

I am sending object with API Body Now I need to get One property from that object and I also need to modify that property in the object how I can do this .
Here is my laravel controller function
public function advanceOrder(Request $request)
{
try{
$result = $request->getContent();
DB::table('advance_orders')->insert(['data'=> $result]);
}catch(Exception $e)
{
DB::table('advance_orders')->insert(['data'=> $e->getMessage()]);
}
}
Here is the object I am getting from api
I want to get delivery_datetime property from object and also want to modify property in that object
{"paymethod_id":1,"business_id":76,"delivery_type":1,"driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":"2020-12-09 00:23:00","location":{"lat":18.7675049,"lng":-103.1445221},"deliveryOptionmodal":{"id":2,"value":"Esperar en la entrada","$$hashKey":"object:701"},"delivery_cost_new":20,"products":"[{\"id\":48732,\"code\":\"NLNyEp\",\"quantity\":1,\"options\":[],\"ingredients\":[]}]","customer_id":129731,"customer":"{\"id\":129731,\"name\":\"bil\",\"middle_name\":null,\"lastname\":\"ar\",\"second_lastname\":null,\"photo\":null,\"email\":\"bilal1212#gmail.com\",\"cellphone\":\"0213123132131\",\"address\":\"Coalcomán, Michoacán, Mexico\",\"location\":\"{\\\"lat\\\":18.7675049,\\\"lng\\\":-103.1445221}\",\"internal_number\":null,\"address_notes\":\"sss\",\"zipcode\":null,\"map_data\":{\"library\":\"google\",\"place_id\":\"ChIJz6WGrUw-MIQR_jYIoFZ-RPM\"},\"tag\":\"home\"}"}
You need to deserialize your object first because the getContent() method returns a string. Just use json_decode() method.
$result = json_decode($request->getContent(), true);
And from now on you can use data from your JSON object as array fields.
dd($result['delivery_datetime']);
You can also modify your data and serialize it again if you need to persist a JSON object.
$result = json_decode($request->getContent(), true);
$result['driver_tip'] = 50;
$modifiedResult = json_encode($result);
dd($modifiedResult);
You can use like this,
public function advanceOrder(Request $request){
try{
$result = json_decode($request->getContent(), true);
$your_final_result = $result['delivery_datetime'];
dd($your_final_result );
}catch(Exception $e)
{
DB::table('advance_orders')->insert(['data'=> $e->getMessage()]);
}
}

save mathod in database cause Array to string conversion error in laravel

when I execute custom command with
php artisan query:all
every thing is good except error shown in console the error is
Array to string conversion
and the data is stored to database I did not understand the cause of this error and it's hidden when hide save to database method
the code of my service which the problem cause inside it is
<?php
namespace App\Services;
use Carbon\Carbon;
use GuzzleHttp\Client;
use App\Models\weatherStatus;
use Illuminate\Support\Collection;
class ApixuService
{
public function query(string $apiKey, Collection $cities): Collection
{
$result = collect();
$guzzleClient = new Client([ //create quzzle Client
'base_uri' => 'http://api.weatherstack.com'
]);
foreach ($cities as $city) {
$response = $guzzleClient->get('current', [
'query' => [
'access_key' => $apiKey,
'query' => $city->name,
]
]);
$response = json_decode($response->getBody()->getContents(), true); //create json from $response
$status = new weatherStatus(); //create weatherStatus object
//adding prameters
$status->city()->associate($city);
$status->temp_celsius = $response['current']['temperature'];
$status->status = $response['current']['weather_descriptions'];
$status->last_update = Carbon::createFromTimestamp($response['location']['localtime_epoch']);
$status->provider = 'weatherstack.com';
//save prameters
$status->save();
$result->push($status);
}
return $result;
}
}
So you can find some clarity in what you are trying to save, do the following:
$response = json_decode($response->getBody()->getContents(), true);
dd($response);
dd() will dump all the data from the $response and exist the script.
One of the values you are trying to save is an array. The field you are trying to save accepts a string and not array.

laravel and json array

I am using laravel 5.3 and angularjs
I submit json from my angularjs like below
{"grc":{"id":1},"floatingGrcs":[{"days":"10","units":"100"},{"days":"20","units":"200"}]}
I accept this array from my laravel controller like below
public function store(Request $request)
{
//how to extract $request object in here
}
I don't know how to extract submitted json array in laravel controller
You can use standard json_decode():
public function store(Request $request)
{
$data = json_decode($request->someJson);
}
You can look at all available data with dd($request->all());
The common-case is that there is no need to post json-encoded data through Angular.
To submit something with Angular, you should use, for example:
$http.post('api/something', {"grc":{"id":1},"floatingGrcs": [..]})
And then there is no need to decode json on the Laravel side:
public function store(Request $request)
{
$request->all(); // to get all fields
$request->grc->id; // to get a specific field
}
I got answer with below code. But i am not sure
$params = json_decode(file_get_contents('php://input'), TRUE);
is this above line of code secure or not.
public function store()
{
$params = json_decode(file_get_contents('php://input'), TRUE);
foreach ($params as $key => $value)
{
if($key == "grc")
{
$grc_id = $value["id"];
}
elseif($key == "floatingGrcs")
{
foreach ($value as $floating)
{
$days = $floating["days"];
}
}
}

CakePHP 2.5 Datasource, create and return response

I have a specific task to connect CakePHP web application to a remote restful server . I create a datasource, read method works great, but the api after save data return an array of processed data.
Looking for a way to return the data array and use in controller.
My Controller code
public function admin_generate()
{
$data = $this->request->data;
$data['path'] = 'special/generate';
$this->Tool->create();
if($this->Tool->save($data)){
// handle response ????
}
$this->set('data',$data);
$this->set('_serialize','data');
}
In datasource file
public function create(Model $model, $fields = null, $values = null)
{
$data = array_combine($fields, $values);
$api = $this->config['api_path'].$data['path'].'?auth_key='.$this->config['auth_key'];
$json = $this->Http->post($api, $data);
$response = json_decode($json, true);
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
return $response; // ??????
}
Can someone show me the correct way to use the api response data in the controller?
I found a solution, a few minutes after a post question. This can help one of you.
datasource
....
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
// SOLUTION
$model -> code = $response['code'];
$model -> key = $response['key'];
$model -> code_id = $response['code_id'];
return true;
.....
in controller
.....
if($this->Tool->save($data)){
unset($data['path']);
$data['code'] = $this->Tool->code;
$data['key'] = $this->Tool->key;
$data['code_id'] = $this->Tool->code_id;
}
.....

using HTTPRequest setPayload in google app engine

I am trying to do HTTPRequest Post via Google App Engine.
This is what I have so far
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Here I need to put some paired values (ie. "email","hi#example.com" etc)
Since setPayload accept byte[] I have no idea how to convert my paired values
into byte.
I have searched other posts but I am very stuck.
EDIT:
I have changed to this but it is still not working
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
This is what I have on php website.
<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>
EDIT2: This is a working code
try{
byte[] data = ("EMAIL=bo0#gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}
My database string field is of type UTF-8
You create a String with the request body, and then you get the byte array. For example we have:
URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
Hope this helps!

Resources