在Groovy中实现Object-JSON映射的标准方法是什么?

时间:2014-05-08 01:11:03

标签: java json groovy

在Java中,如果我想将一些JSON转换为POJO(或副版本),我将使用Gson甚至FlexJson在某种mapper对象中为我进行转换:

public interface JsonMapper<T> {
    public T toPojo(String json);
    public String toJson(T pojo);
}

public class WidgetJsonMapper implements JsonMappper<Widget> {
    private Gson mapper;

    @Override
    public Widget toPojo(String json) {
        // Use mapper to deserialize JSON into POJO
    }

    @Override
    public String toJson(Widget pojo) {
        // Use mapper to serialize a Widget instance into a JSON string.
    }
}

等。当我们谈论Groovy时,我想知道游戏是如何改变的。我看到Grooovy内置了一个JsonSlurper,并想知道是否可以用某种方式代替JSON映射框架(如Gson)。

1 个答案:

答案 0 :(得分:9)

Gson也可以在Groovy中用于将JSON解析为POGO,反之亦然。分别与JsonSlurper和JsonBuilder相同。使用两种方式的示例:

@Grab( 'com.google.code.gson:gson:2.8.0' )
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

class Book {
    String name
    int isbn
    List<Author> authors
}

class Author {
    String name
    int age
}

def jsonString = '''
{
    "name": "Groovy", 
    "isbn": 12345, 
    "authors": [{
        "name": "John Doe", 
        "age": 30
     }, {
        "name": "Bill Nash", 
        "age": 40
     }] 
}
'''

//To Test
void assertions( book ) {
  book.with {
    assert name == 'Groovy'
    assert isbn == 12345
    assert authors
    assert authors[0].name == 'John Doe'
    assert authors[0].age == 30
    assert authors[1].name == 'Bill Nash'
    assert authors[1].age == 40
  }
}

/* JSON To POGO*/
//Using JsonSlurper
def book = new Book( new JsonSlurper().parseText( jsonString ) )
assertions book

//Using GSON
Gson gson = new Gson()
def bookUsingGson = gson.fromJson( jsonString, Book )
assertions bookUsingGson 

/* POGO To JSON */
//Using JsonBuilder
println new JsonBuilder( book ).toPrettyString()

//Using Gson
println gson.toJson( bookUsingGson )

//Using GsonBuilder for customization
GsonBuilder builder = new GsonBuilder()

// enable pretty print and seriliaze nulls
builder.setPrettyPrinting().serializeNulls()

// customize field title
builder.fieldNamingStrategy = { field -> field.name == "name" ? "title" : field.name }

// use the GsonBuilder to create a gson
Gson gsonBuilder = builder.create()

// pretty print
println gsonBuilder.toJson( bookUsingGson )