2016-07-30 65 views
-2

這看起來像是重複的,但我試過其他答案無濟於事。我使用Xamarin和PHP。我的PHP查詢有效,但它沒有正確返回格式化的PHP。我使用PHP 5.6並檢查JSON。我的PHP是:PHP沒有編碼到JSON

$stmt=$conn->prepare("SELECT id,user,water,poop FROM dailyMisc WHERE user = ? AND misc_day = ?"); 
$stmt->bind_param('is',$userId,$dateSelected); 

$stmt->execute(); 
$stmt->bind_result($idR,$user_idR,$waterR,$poopR); 
$stmt->store_result(); 

    while($stmt->fetch()) 
    { 
     $misc[] = array('Id'=>$idR,'UserId'=>$user_idR,'Water'=>$waterR,'Poop'=>$poopR); 
     echo json_encode($misc); 
    } 

PHP回報:

[{"Id":25,"UserId":24,"Water":0,"Poop":1}]

我Xamarin錯誤:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'BitesBoardMobile.businessObject.BusinessMisc' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

+1

變化'$雜項[]''到$ misc'。此外,如果你想要多個值,那麼我建議在while('$ misc = array();')之前聲明'$ misc',然後使用'array_push($ misc,array('Id'=> ... = > $ poopR);''你可以用數組填充數組(如果你不確定while循環的迭代次數)。另外,如果你這樣做,你必須在while循環之後echo'$ misc'。 – ForceMagic

回答

-1

的問題是,你的陣列格式不正確。

$misc = ['Id'=>$idR,'UserId'=>$user_idR,'Water'=>$waterR,'Poop'=>$poopR]; 
echo json_encode($misc); 
0

該錯誤消息似乎有你需要的所有信息:的類型要求一個JSON對象(例如{「名稱」:「值」})。您正嘗試將JSON 數組傳遞給期望JSON對象的函數。

php returns [{"Id":25,"UserId":24,"Water":0,"Poop":1}]

那些方括號表示你發送的是數組而不是對象。一個對象是這樣的(注意沒有方括號中):

{"Id":25,"UserId":24,"Water":0,"Poop":1} 

幸運的是,你想要的目的是,數組的第一個和唯一的成員,因此,您可以採取(大概json_encode($misc[0]))或投$misc如在第一位置的對象,通過取括號關閉其聲明($misc =,不$misc[] =)的:

$misc = array('Id'=>$idR,'UserId'=>$user_idR,'Water'=>$waterR,'Poop'=>$poopR);