Backend Development 4 min read

Adding Custom Methods to fastjson JSONObject Using Groovy MetaClass

This article demonstrates how to dynamically add custom methods to fastjson's JSONObject in Groovy by leveraging MetaClass and closures, providing code examples that simplify JSON traversal and output during API testing for developers.

FunTester
FunTester
FunTester
Adding Custom Methods to fastjson JSONObject Using Groovy MetaClass

The article builds on a previous tutorial about Groovy dynamic method and property addition, and shows how to use fastjson to add a custom method to JSONObject for more efficient programming.

Requirement

fastjson's com.alibaba.fastjson.JSONObject does not provide a direct iteration method, so developers often need to write explicit loops or lambda expressions to print parts of a JSON response during API testing.

Sample JSON Data

def params = new JSONObject()
params.code= 1
params.msg= "FunTester"
def data = new JSONObject()
data.name = "张三"
data.age = 22
params.data = []
params.data << data
params.data << data.clone()
params.data << data.clone()

Printing the above JSON yields a formatted output showing the msg , code , and an array of data objects.

Direct Implementation of Output Method

The solution uses groovy.lang.MetaClass to inject a new method into JSONObject :

JSONObject.metaClass.fun = {
    def array = params.getJSONArray("data")
    array.each {
        sleep(1.0)
        output(Time.getNow(Time.DEFAULT_FORMAT.get()))
        output(it)
    }
}

params.fun()

Running this prints each element of the data array with timestamps, as shown in the console logs.

Flexible Implementation Using Closures

By employing groovy.lang.Closure , the same functionality can be expressed more concisely:

JSONObject.metaClass.fun2 = { f ->
    def array = params.getJSONArray("data")
    array.each {
        f(it)
    }
}

params.fun2({x -> output(x.get("name"))})
params.fun2({output(it.get("age"))})

The console output displays the names and ages of the objects in the JSON array.

Conclusion

Using Groovy's MetaClass and closures to extend fastjson.JSONObject provides a powerful way to add custom traversal and printing methods, reducing boilerplate code and improving readability in API testing scripts.

fastjsonGroovymetaclassDynamicMethodJSONObject
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.