如何在Swift或Php中将核心数据编码为JSON而不使用斜线

问题描述:

如果JSON具有“/ n”和“/”,则我的php将返回错误。我不确定我需要更改我的PHP代码或我的swift代码。如何在Swift或Php中将核心数据编码为JSON而不使用斜线

我的PHP代码

$json = file_get_contents('php://input'); 
$obj = json_decode($json, true); 
print_r($obj); 

它看起来像无法解码?

Array ([0] => {"user":"1","accbooktype":"æµæ°´è´¦æœ¬","accbookname":"日常","accbookid":"1","category":"日常","cid":"U1L2B555"}) 

enter image description here

成功输出:

Array ([0] => Array ([cid] => 5 [accbookname] => test [accbooktype] => test [category] => test [user] => test)) 

enter image description here

这是我的SWIFT代码。如果在这里更改代码。我需要知道如何将核心数据编码为不带斜杠的JSON,如何?

//newdict is Core data 
let jsonData = try JSONSerialization.data(withJSONObject: newdict, options: [.prettyPrinted]) 

//I tried this also but not worked 
//let jsonEncoder = JSONEncoder() 
//let jsonData = try jsonEncoder.encode(newdict) 

let jsonString = String(data: jsonData, encoding: .utf8) 
bookJSON.append(jsonString!) 

print(bookJSON) 

输出:

["{\n \"cid\" : \"U1L2B1\",\n \"user\" : \"1\",\n \"accbooktype\" : \"流水账本\",\n \"accbookname\" : \"日常\",\n \"accbookid\" : \"1\",\n \"category\" : \"日常\"\n}"] 

对此

[ 
    { 
     "cid": "5", 
     "accbookname" : "test", 
     "accbooktype": "test", 
     "category": "test", 
     "user": "test" 
    } 
] 
+1

你已经从file_get_contents('php:// input')获得了两次编码的json; 删除另一端的json编码,在那里您调用端点并传递数据。另外,由于特殊字符的原因,在传递到端点之前,您可能需要将数据编码为utf8。 – Eimsas

+0

我不需要在Swift中将字典编码为JSON? @Eimsas –

你可以试试这个

header('Content-Type: application/json'); 
$request = json_decode(file_get_contents('php://input'), true); 
print_r($request); 

你可以人所以使用类型铸造

$request = (array) json_decode(file_get_contents('php://input'), true); 
+0

同样的错误讯息.. –