JsonGenerator not recognized in external code, does not compile
Hi,
At this moment I am rewriting code that generates json body content, after reading values from an Excel file. Originally everything is written by using String operations, which makes the code horribly complicated. I want to remove this anti pattern with code generated by JsonBuilder. I did this using an external code compiler and it works (beautifully) then.
It looks something like this:
import groovy.json.JsonBuilder;
import groovy.json.JsonBuilder.*;
import groovy.json.*
public static String generateSomeContent(def travelClassValue, def productFamilyList)
def generator = new JsonGenerator.Options().excludeNulls().build()
JsonBuilder builder = new JsonBuilder(generator)
def root = builder.productOptions {
travelClass travelClassValue
productFamilies productFamilyList
}
return JsonOutput.prettyPrint(generator.toJson(root).toString())
If I want to call this (alike) method from ReadyApi. Unfortunatly this generates a compiler error, which I do not get when using an external compiler: 'unable to resolve class JsonGenerator.Options'
I can use JsonBuilder class and that works well in ReadyApi, but I really need to use JsonGenerator class for the option excludeNulls, otherwise I have to resort to all kind of null pointer checks - which will complicate the code again.
I suppose it has to do something with library imports, but I don't know which library I should import and how to do that.
I can't find similar threads on this subject, so here is my call for help...
Hi Msiadak,
I give up on my old solution. Putting jar files in SoapUI is a bit too circumspect, as the code has to be easily shared with others. It's good to know for sure I cannot use all groovy logic of version 2.5. Thx.
My new solution is somewhat like an older solution I have posted myself earlier.
I put the structure in hasmaps (conditionally), and add this to a JsonBuilder object. Then I prettyprint this structure. Not as accessible as the intended solution, but better than adding jsonbuilding logic in a String.
dummy code:
import groovy.json.JsonBuilder;
import groovy.json.JsonBuilder.*;
import groovy.json.*
public static String generateSomeContent(def travelClassValue, def productFamilyList)
def rootMap = [:]
if (travelClassValue) rootMap.travelClass = travelClassValue
if (productFamilyList) rootMap.productFamily = productFamilyList.split(',')
JsonBuilder builder = new JsonBuilder(rootMap)
return JsonOutput.prettyPrint(builder.toString())