【问题标题】:Is there a way to use Marshaller in Grails to parse JSON string into a custom object有没有办法在 Grails 中使用 Marshaller 将 JSON 字符串解析为自定义对象
【发布时间】:2020-02-16 10:55:17
【问题描述】:

我正在尝试将 JSON 字符串解析为我的自定义对象 我已经有一个 Marshaller 类从对象转到 JSON 并且想知道是否可以使用它来解析其他方向而不是使用 JsonSlurper 没有看到任何关于该 API 或任何其他 JSON 到对象映射 API 的明确文档,其中不包括使用 JsonSlurper 编写代码来手动创建对象

【问题讨论】:

    标签: json grails groovy


    【解决方案1】:

    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"}'
    

    对于编组/解组方法,我更喜欢使用 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"}'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      相关资源
      最近更新 更多