JSON 到 Groovy 解析器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1884979/
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 17:22:27  来源:igfitidea点击:

JSON to Groovy parser

jsongroovy

提问by Gzorg

I found many things about converting Groovy to JSON, but oddly enough, not the other way.

我发现了很多关于将 Groovy 转换为 JSON 的事情,但奇怪的是,不是相反。

What is the (best) JSON to Groovy parser around there ?

那里最好的 JSON 到 Groovy 解析器是什么?

采纳答案by Dónal

Because compiled Groovy classes are compatible with Java classes, you should be able to use any Java library for converting JSON to POJOs (or POGOs). Hymansonis a fairly popular choice which you can use to convert JSON like this:

因为编译的 Groovy 类与 Java 类兼容,所以您应该能够使用任何 Java 库将 JSON 转换为 POJO(或 POGO)。Hymanson是一个相当流行的选择,您可以使用它来像这样转换 JSON:

String json = '{
  "name" : { "first" : "Joe", "last" : "Sixpack" },
  "gender" : "MALE",
  "verified" : false,
  "userImage" : "Rm9vYmFyIQ=="
}'

to a Map using:

到地图使用:

Map<String,Object> userData = mapper.readValue(json, Map.class)

Or if you want to convert the JSON to a Groovy User class:

或者,如果您想将 JSON 转换为 Groovy User 类:

User userData = mapper.readValue(json, User.class)

This will map properties in the Groovy class to keys in the JSON.

这会将 Groovy 类中的属性映射到 JSON 中的键。

回答by Fa11enAngel

If you are on Groovy 1.8 or later, there is a build in JsonSlurper you can use this way:

如果您使用的是 Groovy 1.8 或更高版本,则可以通过以下方式使用 JsonSlurper 中的构建:

import groovy.json.JsonSlurper

//Attention: you have to use double quotes inside the json string
def jsonObj = new JsonSlurper().parseText( '{ "name":"Peter", "age": 23}' )

assert jsonObj.name == "Peter"
assert jsonObj.age == 23
//this won't work, because it's not defined
assert jsonObj.gender == null

回答by nes1983

JSON-libclaims to be able to transform POGO to JSON and back. If POGO means what I think it does (Plain Old Groovy Object), you're set :).

JSON-lib声称能够将 POGO 转换为 JSON 并返回。如果 POGO 意味着我认为它的作用(Plain Old Groovy Object),那么你已经准备好了 :)。

They give this example:

他们举了这个例子:

def strAsJsonObject = "{integer:1, bool: true}" as JSONObject

Update:

更新

I've tried the lib myself, this is the complete code:

我自己试过这个库,这是完整的代码:

import net.sf.*;
import net.sf.json.*;
import net.sf.json.groovy.*;

println "hi"
GJson.enhanceClasses()
def strAsJsonObject = "{integer:1, bool: true}" as JSONObject
println strAsJsonObject

It'll chase you through a marathon of downloading dependencies (ezmorph, commons lang, commons logger) and once you've resolved them all, this is what you get:

它会在下载依赖项(ezmorph、commons lang、commons logger)的过程中追逐你,一旦你解决了所有这些,你就会得到:

Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{integer:1, bool: true}' with class 'java.lang.String' to class 'net.sf.json.JSONObject'

线程“main” org.codehaus.groovy.runtime.typehandling.GroovyCastException 中的异常:无法将类“java.lang.String”的对象“{integer:1, bool: true}”转换为“net.sf.json”。 JSONObject'

According to The mailing list, you get this for not calling GJsonlib.enhanceClasses(), but I did call that, as you can see above.

根据邮件列表,你得到这个是因为没有调用 GJsonlib.enhanceClasses(),但我确实调用了它,正如你在上面看到的。

I've concluded that it's a worthwhile endeavor to hate Groovy's JSON-lib.

我得出的结论是,讨厌 Groovy 的 JSON-lib 是值得的。

回答by thom_nic

I use JSON-lib in HTTPBuilder, but I use the JSONSlurper class to parse a string to a JSON instance:

我在HTTPBuilder 中使用 JSON-lib ,但我使用 JSONSlurper 类将字符串解析为 JSON 实例:

JSON jsonMapObject = new JsonSlurper().parse( "{integer:1, bool: true}" );

To go from Object to JSON, I do this:

为了从 Object 到 JSON,我这样做:

//from a map:
new JSONObject().putAll( [one:'1', two:'two']).toString()
//from an object:
JSONObject.fromObject( somePOGO ).toString()

回答by Glen

To the people having trouble with json-lib and GJson.enhanceClasses(). Try GJson.enhanceString() instead.

对于 json-lib 和 GJson.enhanceClasses() 有问题的人。尝试 GJson.enhanceString() 代替。

GJson.enhanceString()
def o = "{\"x\": 20.0}" as JSONObject