Groovy - Convert object to JSON string

后端 未结 3 909
灰色年华
灰色年华 2021-01-30 12:23

I\'m pretty used to Grails converters, where you can convert any object to a JSON representation just like this (http://grails.org/Converters+Reference)

return f         


        
相关标签:
3条回答
  • 2021-01-30 12:47

    Do you mean like:

    import groovy.json.*
    
    class Me {
        String name
    }
    
    def o = new Me( name: 'tim' )
    
    println new JsonBuilder( o ).toPrettyString()
    
    0 讨论(0)
  • 2021-01-30 12:50

    You can use JsonBuilder for that.

    Example Code:

    import groovy.json.JsonBuilder
    
    class Person {
        String name
        String address
    }
    
    def o = new Person( name: 'John Doe', address: 'Texas' )
    
    println new JsonBuilder( o ).toPrettyString()
    
    0 讨论(0)
  • 2021-01-30 13:07

    I couldn't get the other answers to work within the evaluate console in Intellij so...

    groovy.json.JsonOutput.toJson(myObject)
    

    This works quite well, but unfortunately

    groovy.json.JsonOutput.prettyString(myObject)
    

    didn't work for me.

    To get it pretty printed I had to do this...

    groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))
    
    0 讨论(0)
提交回复
热议问题