Grails JSON数组 [英] Grails JSON array

查看:124
本文介绍了Grails JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Foo对象列表转换为JSON字符串。我需要将JSON字符串解析回Foos列表。然而在下面的例子中,解析给了我一个JSONObjects列表,而不是Foos。

示例

  List list = [new Foo(first),new Foo(second)] 
def jsonString =(list as JSON).toString()

List parsedList = JSON.parse(jsonString)as List
println parsedList [0] .getClass()// org.codehaus.groovy.grails.web.json.JSONObject

我如何将它解析为Foos?
在此先感谢。

解决方案

我查看了JSON的API文档,可以通过任何方式将JSON字符串解析为特定类型的对象。



因此,您只需自己编写代码即可将每个 JSONObject Foo 。像这样的应该工作:

  import grails.converters.JSON 
import org.codehaus.groovy.grails.web .json。*

class Foo {
def name

Foo(name){
this.name = name
}

String toString(){
name
}
}


List list = [new Foo(first), new Foo(second)]
def jsonString =(list as JSON).toString()

列表parsedList = JSON.parse(jsonString)

/ /从JSONObject列表转换为Foo列表
def foos = parsedList.collect {JSONObject jsonObject - >
new Foo(name:jsonObject.get(name))
}

更通用的解决方案是向 JSON metaClass添加一个新的静态 parse 方法,如下所示,尝试将JSON字符串解析为特定类型的对象列表:

  import grails.converters.JSON 
import org.codehaus.groovy.grails.web.json。*

class Foo {
def name

Foo(name){
this .name = name
}

String toString(){
name
}
}

List list = [new Foo(first),new Foo(second)]
def jsonString =(列表为JSON).toString()


列表parsedList = JSON.parse jsonString)

//定义新方法
JSON.metaClass.static.parse = {String json,Class clazz - >

List jsonObjs = JSON.parse(json)

jsonObjs.collect {JSONObject jsonObj - >

//如果用户没有提供targetClass,请阅读JSON中的'class'proprerty以确定哪种类型转换为
def targetClass = clazz?:jsonObj.get 'class')as class
def targetInstance = targetClass.newInstance()

//设置targetInstance
的属性jsonObj.entrySet()。each {entry - >

if(entry.key!=class){
targetInstance。$ entry.key= entry.value
}
}
targetInstance
}

}

//尝试新的分析方法
List< Foo> foos = JSON.parse(jsonString,Foo)

//确认它有效
断言foos.every {Foo foo - > foo.class == Foo&& foo.name in ['first','second']}

你可以试试上面的代码在常规控制台。几个警告


  • 我只对上面的代码进行了非常有限的测试

  • JSON类在最新的Grails发行版中,我假设您使用的是不被弃用的类。


I'm converting a list of Foo objects to a JSON string. I need to parse the JSON string back into a list of Foos. However in the following example, parsing gives me a list of JSONObjects instead of Foos.

Example

List list = [new Foo("first"), new Foo("second")]
def jsonString = (list as JSON).toString()

List parsedList = JSON.parse(jsonString) as List
println parsedList[0].getClass() // org.codehaus.groovy.grails.web.json.JSONObject

How can I parse it into Foos instead? Thanks in advance.

解决方案

I had a look at the API docs for JSON and there doesn't appear to be any way to parse to a JSON string to a specific type of object.

So you'll just have to write the code yourself to convert each JSONObject to a Foo. Something like this should work:

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

class Foo {
  def name

  Foo(name) {
    this.name = name
  }

  String toString() {
    name
  }
}


List list = [new Foo("first"), new Foo("second")]
def jsonString = (list as JSON).toString()

List parsedList = JSON.parse(jsonString)

// Convert from a list of JSONObject to a list of Foo
def foos = parsedList.collect {JSONObject jsonObject ->
    new Foo(name: jsonObject.get("name"))
}

A more general solution would be to add a new static parse method such as the following to the JSON metaClass, that tries to parse the JSON string to a List of objects of a particular type:

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

class Foo {
  def name

  Foo(name) {
    this.name = name
  }

  String toString() {
    name
  }
}

List list = [new Foo("first"), new Foo("second")]
def jsonString = (list as JSON).toString()


List parsedList = JSON.parse(jsonString)

// Define the new method
JSON.metaClass.static.parse = {String json, Class clazz ->

    List jsonObjs = JSON.parse(json)

    jsonObjs.collect {JSONObject jsonObj ->

        // If the user hasn't provided a targetClass read the 'class' proprerty in the JSON to figure out which type to convert to
        def targetClass = clazz ?: jsonObj.get('class') as Class
        def targetInstance = targetClass.newInstance()        

        // Set the properties of targetInstance
        jsonObj.entrySet().each {entry ->

            if (entry.key != "class") {
                targetInstance."$entry.key" = entry.value
            }
        }
        targetInstance
    }

}

// Try the new parse method
List<Foo> foos = JSON.parse(jsonString, Foo)

// Confirm it worked
assert foos.every {Foo foo -> foo.class == Foo && foo.name in ['first', 'second'] }

You can try out the code above in the groovy console. A few warnings

  • I have only performed very limited testing on the code above
  • There are two JSON classes in the latest Grails release, I'm assuming you're using the one that is not deprecated

这篇关于Grails JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆