【问题标题】:groovy parse json and save to databasegroovy 解析 json 并保存到数据库
【发布时间】:2013-02-22 07:43:44
【问题描述】:

我想将一个 json 文件解析为对象,并将其保存到数据库中。我只是创建了一个在 grails 控制台中运行的 groovy 脚本(在 cmd 行中键入 grails 控制台)。我没有创建 grails 应用程序或域类。在这个小脚本中,当我调用 save 时,我有

groovy.lang.MissingMethodException: No signature of method: Blog.save() 
  is applicable for argument types: () values: []
Possible solutions: wait(), any(), wait(long), isCase(java.lang.Object), 
  sleep(long), any(groovy.lang.Closure)

我错过了什么吗?
我也很困惑,如果我保存,是否会将数据保存到名为 Blog 的表中?我应该在这里建立任何数据库连接吗? (因为我是 grails 域类,我们不需要。但是使用纯 groovy 有什么不同吗?)

非常感谢!

import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; 

class Blog {
  String title
  String body   
 static mapping = {
   body type:"text"
   attachment type:"text"
}

  Blog(title,body,slug){
    this.title = title
    this.body=body   
  }   
}

这里解析json

// parse json
List parsedList =JSON.parse(new FileInputStream("c:/ning-blogs.json"), "UTF-8")

def blogs = parsedList.collect {JSONObject jsonObject ->
    new Blog(jsonObject.get("title"),jsonObject.get("description"),"N/A");
}

循环博客并保存每个对象

for (i in blogs){
    // println i.title; I'll get the information needed.
    i.save();
}

【问题讨论】:

  • 你把Blog类放在哪里了?
  • Blog 是一个 grails 域类吗? “普通”类不会自动拥有save 方法
  • 谢谢,我没有将它指定为域类,我只是创建了一个在 grails 控制台中运行的 groovy 脚本。我可以在 groovy 脚本中的某处指定它吗?我只是希望它是可以运行的简单内部脚本..

标签: mysql grails groovy


【解决方案1】:

我没有丰富的 grails 经验,但从快速谷歌搜索看来,对于一个被视为模型类的类,它需要位于正确的约定包/目录或 legacy jar with hibernate mapping /JPA annotation。因此,您的示例无法正常工作。为什么不在模型包中定义该模型?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多