我提前为一个非常的长问题道歉。希望您能多多包涵。
我正在使用 goweb库,并尝试使用 example web app .
我一直在尝试修改 RESTful example code ,它定义了一个 Thing作为:
type Thing struct {
Id string
Text string
}
一个 Thing 是通过发送一个 HTTP Post 请求和一个适当的 JSON 主体到 http://localhost 创建的:9090/事物。这在 Create function 中的示例代码中处理。 ,特别是行:
dataMap := data.(map[string]interface{})
thing := new(Thing)
thing.Id = dataMap["Id"].(string)
thing.Text = dataMap["Text"].(string)
一切都很好,我可以运行示例服务器(它在 http://localhost:9090/ 上监听)并且服务器按预期运行。
例如:
curl -X POST -H "Content-Type: application/json" -d '{"Id":"TestId","Text":"TestText"}' http://localhost:9090/things
没有错误返回,然后我GET那个Thing
curl http://localhost:9090/things/TestId
它返回
{"d":{"Id":"TestId","Text":"TestText"},"s":200}
到目前为止,还不错。
现在,我想修改 Thing 类型,并添加自定义 ThingText 类型,如下所示:
type ThingText struct {
Title string
Body string
}
type Thing struct {
Id string
Text ThingText
}
这本身不是问题,我可以像这样修改 Create 函数:
thing := new(Thing)
thing.Id = dataMap["Id"].(string)
thing.Text.Title = dataMap["Title"].(string)
thing.Text.Body = dataMap["Body"].(string)
并运行之前的 curl POST 请求,将 JSON 设置为:
{"Id":"TestId","Title":"TestTitle","Title":"TestBody"}
它返回时没有错误。
我可以再次GET Thing URL 并返回:
{"d":{"Id":"TestId","Text":{"Title":"TestTitle","Body":"TestBody"}},"s":200}
同样,到目前为止,一切都很好。
现在,我的问题:
我如何修改 Create 函数以允许我向它POST 复杂的 JSON?
例如,上面最后返回的 JSON 字符串包括 {"Id":"TestId","Text":{"Title":"TestTitle","Body":"测试体"}}。 我希望能够POST 那个确切的 JSON 到端点并拥有 Thing已创建。
我已经按照代码返回,data 变量似乎是来自 https://github.com/stretchr/goweb/context 的 Context.RequestData() 类型,并且内部 Map 似乎是 Object.Map 类型来自 https://github.com/stretchr/stew/ , 描述为 "a map[string]interface{} with additional helpful functionality."特别是,我注意到 "Supports dot syntax to set deep values."
我不知道如何设置 thing.Text.Title = dataMap... 语句以便将正确的 JSON 字段解析到其中.除了 dataMap 中的 string 类型,我似乎无法使用任何其他类型,如果我尝试使用 JSON,它会给出类似于以下内容的错误:
http: panic serving 127.0.0.1:59113: interface conversion: interface is nil, not string
再次抱歉,这个问题太长了。非常感谢您的阅读,以及您可能提供的任何帮助。谢谢!
最佳答案
作为JSON package documentation和 JSON and Go introduction描述,JSON 数据可以通过接口(interface){}/字符串映射进行一般解析,也可以直接解码为结构类型。
您链接到的示例代码以及您基于您的更改似乎使用了通用的字符串映射方法,dataMap := data.(map[string]interface{})。
由于您所需的 JSON 数据是对象中的对象,因此它只是 map 中的 map 。
所以你应该能够
dataMap := data.(map[string]interface{})
subthingMap := dataMap["Text"].(map[string]interface{})
thing.Text.Title = subthingMap["Title"].(string)
thing.Text.Body = subthingMap["Body"].(string)
我不确定为什么该代码使用强制转换和泛型类型,而不是直接从 JSON 到结构类型(我猜是抽象)的类型安全解码。使用 json 包解码来构造类型会是这样的
type ThingText struct {
Title string
Body string
}
type Thing struct {
Id string
Text ThingText
}
…
decoder := json.NewDecoder(body)
var thingobj Thing
for {
if err := decoder.Decode(&thingobj); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Println(thingobj)
}
其中 body 是一个 io.Reader - 在简单/大多数情况下来自 http.Response.Body。
关于json - 将复杂的 JSON 解析为 goweb REST Create() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17252915/
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只