有没有办法在 Grails 中使用 Marshaller 将 JSON 字符串解析为自定义对象
Is there a way to use Marshaller in Grails to parse JSON string into a custom object
我正在尝试将 JSON 字符串解析为我的自定义对象
我已经有一个 Marshaller class 从对象到 JSON
并且想知道是否可以将它用于其他方向的解析而不是使用 JsonSlurper
没有看到关于此或任何其他 JSON 到对象映射 api 的明确文档,其中不包括使用 JsonSlurper 编写代码以手动创建对象
groovy 支持这样的简单映射:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
class A{
int id
String name
}
Map m = new JsonSlurper().parseText('{"id":123,"name":"Joe"}')
A a = m as A
assert a.id==123
assert a.name=="Joe"
def json = JsonOutput.toJson(a)
assert json == '{"id":123,"name":"Joe"}'
对于marshalling/unmarshalling方法我更喜欢使用Gson库:
@Grab(group='com.google.code.gson', module='gson', version='2.8.5')
import com.google.gson.Gson
class A{
int id
String name
}
A a=new Gson().fromJson('{"id":123,"name":"Joe"}', A.class)
assert a.id==123
assert a.name=="Joe"
def json = new Gson().toJson(a)
assert json == '{"id":123,"name":"Joe"}'
我正在尝试将 JSON 字符串解析为我的自定义对象 我已经有一个 Marshaller class 从对象到 JSON 并且想知道是否可以将它用于其他方向的解析而不是使用 JsonSlurper 没有看到关于此或任何其他 JSON 到对象映射 api 的明确文档,其中不包括使用 JsonSlurper 编写代码以手动创建对象
groovy 支持这样的简单映射:
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
class A{
int id
String name
}
Map m = new JsonSlurper().parseText('{"id":123,"name":"Joe"}')
A a = m as A
assert a.id==123
assert a.name=="Joe"
def json = JsonOutput.toJson(a)
assert json == '{"id":123,"name":"Joe"}'
对于marshalling/unmarshalling方法我更喜欢使用Gson库:
@Grab(group='com.google.code.gson', module='gson', version='2.8.5')
import com.google.gson.Gson
class A{
int id
String name
}
A a=new Gson().fromJson('{"id":123,"name":"Joe"}', A.class)
assert a.id==123
assert a.name=="Joe"
def json = new Gson().toJson(a)
assert json == '{"id":123,"name":"Joe"}'