【问题标题】:Parse JSON string to Database将 JSON 字符串解析到数据库
【发布时间】:2011-09-06 12:05:34
【问题描述】:

我在将 JSON 字符串解析到我的 MYSQL 数据库时遇到问题。 这是发送到服务器的 JSON 字符串:

    [{"Description":"Detta är mitt quiz!","Title":"Mitt Quiz","Category":"Music","Language":"Swedish","Difficulty":1},{"QuestionNr1":{"WrongAnswer3":"Visby","WrongAnswer1":"Stockholm","RightAnswer":"Uppsala","WrongAnswer2":"Umeå","Question":"Vilken stad bor jag i?"},"QuestionNr2":{"WrongAnswer3":"Visby","WrongAnswer1":"Stockholm","RightAnswer":"Uppsala","WrongAnswer2":"Umeå","Question":"Vilken stad bor jag inte i?"}}]

这是调用[mArrayJSonrepresentation]之前的数据;就在上面

(
    {
    Category = Music;
    Description = "Detta \U00e4r mitt quiz!";
    Difficulty = 1;
    Language = Swedish;
    Title = "Mitt Quiz";
},
    {
    QuestionNr1 =         {
        Question = "Vilken stad bor jag i?";
        RightAnswer = Uppsala;
        WrongAnswer1 = Stockholm;
        WrongAnswer2 = "Ume\U00e5";
        WrongAnswer3 = Visby;
    };
    QuestionNr2 =         {
        Question = "Vilken stad bor jag inte i?";
        RightAnswer = Uppsala;
        WrongAnswer1 = Stockholm;
        WrongAnswer2 = "Ume\U00e5";
        WrongAnswer3 = Visby;
    };
}

)

我正在使用 ASIHTTPRequest 的 POST 方法,但不知道如何在服务器端接收它并使用 PHP 将其解析到我的数据库中。

谁能指出我正确的方向,我会很高兴!

//谢谢!

【问题讨论】:

    标签: php mysql objective-c xcode json


    【解决方案1】:

    http://php.net/manual/en/function.json-decode.php

    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    var_dump(json_decode($json));
    

    循环 $json 并构建 sql 查询

    【讨论】:

    • 那么but don't know how to receive this on the server side 呢?
    【解决方案2】:

    除非您在命名变量中POSTing JSON 字符串,否则内容将在请求负载中可用,可从stdin 读取。

    // Read contents from stdin
    $json_string = file_get_contents('php://input');
    

    如果您将 JSON 字符串作为命名的 POST 变量发送,则其内容位于 $_POST['varname'] 中。

    要在 PHP 中解析 JSON 字符串,您将使用 json_decode 函数。可以使用json_last_error 函数检查解析是否成功。

    // Parse a JSON-string into PHP native equivalents
    $json_parsed = json_decode($json_string);
    
    if (json_last_error() === JSON_ERROR_NONE) {
        var_dump($json_parsed);
    } else {
        // Error parsing JSON
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      相关资源
      最近更新 更多