将JSON字符串解析为数据库

时间:2011-09-06 12:05:34

标签: php mysql objective-c xcode json

我在将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?"}}]

这是调用[mArray JSonrepresentation]之前的数据;在它上面

(
    {
    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将其解析到我的数据库。

有人能指出我正确的方向,我会非常高兴!

//谢谢!

2 个答案:

答案 0 :(得分:0)

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查询

答案 1 :(得分:0)

除非您在命名变量中POST使用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
}