0

嗨,我找到了一个关于如何在 lua 中使用 post json 的教程。

这是代码:

http = require("socket.http")
crypto = require("crypto")
ltn12 = require("ltn12")
url = require("socket.url")
local json = require("json")

local commands_json = 
{

                ["message"] = "Hello",

}
print (commands_json)
local json = {}
json.api_key = "6_192116334"
json.ver = 1
json.commands_json = json.encode(commands_json)
json.commands_hash = crypto.digest(crypto.md5, json.commands_json .. 'hkjhkjhkjh')

local post = "api=" .. url.escape(Json.Encode(json))
local response = {}

local r, c, h = http.request {
    url = "http://127.0.0.1/?page=api",
    method = "POST",
    headers = {
        ["content-length"] = #post,
        ["Content-Type"] =  "application/x-www-form-urlencoded"
    },
    source = ltn12.source.string(post),
    sink = ltn12.sink.table(response)
}

local path = system.pathForFile("r.txt", system.DocumentsDirectory)
local file = io.open (path, "w")
file:write (Json.Encode(json) .. "\n")
file:write (post .. "\n")
file:write (response[1] .. "\n")
io.close (file)

json = Json.Decode(table.concat(response,''))
native.showAlert("hey", json.commands[1].tot_nbr_rows)

现在我得到了这些错误:

Windows simulator build date: Dec  9 2011 @ 14:01:29


Copyright (C) 2009-2011  A n s c a ,  I n c .
        Version: 2.0.0
        Build: 2011.704
table: 0346D6D0
Runtime error
        ...nistrator\my documents\corona projects\json\main.lua:17: attempt to c
all field 'encode' (a nil value)
stack traceback:
        [C]: in function 'encode'
        ...nistrator\my documents\corona projects\json\main.lua:17: in main chun
k
Runtime error: ...nistrator\my documents\corona projects\json\main.lua:17: attem
pt to call field 'encode' (a nil value)
stack traceback:
        [C]: in function 'encode'
        ...nistrator\my documents\corona projects\json\main.lua:17: in main chun
k

我不知道为什么我从encode.

任何人都可以帮助我处理我的情况吗?

提前致谢 ...

4

1 回答 1

5

这包括外部提供的 Json 代码,可能带有编码功能:

local json = require("json")

这会丢弃旧json变量并将其替换为空表:

local json = {}

这会尝试调用json.encodewhich 现在未定义,因为您json在上面重新定义为空表:

json.commands_json = json.encode(commands_json)

解决方案是选择不同的变量名。

于 2012-05-03T12:30:21.907 回答