donglikuang8145 2012-12-18 07:52
浏览 48
已采纳

JSON编码的最佳格式?

I'm not familiar with PHP and JSON but need it for my Android project.

I'm confused about which JSON format is the most effective. Most examples I saw use Associative array by using this code:

$result = mysql_query($queryString)
while($row = mysql_fetch_assoc($result)){
    $json['contact']['ID'] = $row['ID'];
    $json['contact']['Name'] = $row['Name'];
}

Format #1

{"contact":{"ID":"1","Name":"Andy"}}

I like that format but I don't know how to make each key hold more than one value. So when my query returns Andy and Bob, the json will only contains Bob.

Then, I found this PHP code:

while($row = mysql_fetch_row($result)){
    $json['contact'][] = $row;
}
echo json_encode($json);

It makes the json looks like this:

Format #2

{"contact":[["1","Andy"],["2","Bob"]]}

But in Android, there is no JSONObject method to getArray(). Even if there is, I want to avoid using numbered array that requires [0] or [1] to be called.

So, which one is better? Or any other alternative?

Thanks

  • 写回答

4条回答 默认 最新

  • dt3999 2012-12-18 07:57
    关注

    It's not that one method is more "effective" than the other, they serve different purposes. One is an associative object, and the other is a indexed array.

    In your case, it looks like you want a list (indexed array) of objects. So what i would recommend doing is:

    $result = mysql_query($queryString)
    while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
        $json['contact'][] = $row;
    }
    echo json_encode($json);
    

    which would result in the json:

    {"contact":[{"ID":"1","Name":"Andy"}, {"ID":"2","Name":"Bob"}]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端