Groovy - 将对象转换为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20999543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:09:20  来源:igfitidea点击:

Groovy - Convert object to JSON string

jsongroovy

提问by Wavyx

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)

我非常习惯于 Grails 转换器,您可以在其中将任何对象转换为 JSON 表示,就像这样(http://grails.org/Converters+Reference

return foo as JSON

But in plain groovy, I cannot find an easy way to do this (http://groovy-lang.org/json.html)

但是在普通的 groovy 中,我找不到一种简单的方法来做到这一点(http://groovy-lang.org/json.html

JSONObject.fromObject(this)

return empty json strings...

返回空的 json 字符串...

Am I missing an obvious Groovy converter ? Or should I go for Hymanson or gson library ?

我错过了一个明显的 Groovy 转换器吗?还是我应该去 Hymanson 或 gson 图书馆?

回答by tim_yates

Do you mean like:

你的意思是像:

import groovy.json.*

class Me {
    String name
}

def o = new Me( name: 'tim' )

println new JsonBuilder( o ).toPrettyString()

回答by chim

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

我无法在 Intellij 的评估控制台中获得其他答案,所以......

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))

回答by dhamibirendra

You can use JsonBuilderfor that.

您可以为此使用JsonBuilder

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()