我创建了一个类
class EpayOrderPayRequest
{
public $platformId;
public $accountId;
public $orderInfos;
//方法是对应的get和set
}
//创建实例
$request = new EpayOrderPayRequest();
$request->setPlatformId("PlatformId");
$request->setAccountId("AccountId");
//orderInfo的内容是一个json格式
$orderInfo = array(
"goodsName" => "testgoods",
"goodsType" => "00",
"tradeAmount" => 0.02
);
$orderInfos = json_encode($orderInfo);
$request->setOrderInfos("[".$orderInfos."]");
$jsonStr = json_encode($request);
echo $jsonStr;
}
输出是这样的:
{
"platformId":"platformId",
"accountId":"accountId",
"orderInfos":
"[{"goodsName":"testgoods",
"goodsType":"00",
"tradeAmount":0.02"
}]"}
orderInfos中括号外面带了个双引号,导致json格式解析出差,问下有什么解决办法?
你是不是想要这样的,
$orderInfo = array(
'goodsName' => 'testgoods',
'goodsType' => '00',
'tradeAmount' => 0.02
);
$a = array(
"platformId"=>"platformId",
"accountId"=>"accountId"
);
$a['orderInfo'] = $orderInfo;
$jsonStr = json_encode($a);
echo ($jsonStr);
我是根据你的随便弄了数组,你需要先把这两个数组合并,然后json_encode();
你最后想要输出的格式是什么?orderinfo赋值改成这样
$orderInfo[] = array(
"goodsName" => "testgoods",
"goodsType" => "00",
"tradeAmount" => 0.02
);
$orderInfos = json_encode($orderInfo);//这句去掉
只要是数组就能正确转换成json,不管是几维的,orderInfo保留数组格式,类的最终返回值统一成数组,最后转json。
试了下,对象包含数组的形式也可直接用json_encode,你把代码改成下面的
$orderInfo = array(
"goodsName" => "testgoods",
"goodsType" => "00",
"tradeAmount" => 0.02
);
$request->setOrderInfos($orderInfos);
$jsonStr = json_encode($request);