Groovy: Convert String / Map to Jsonobject
Def stringJson = '''{"Student": {"Name": "","Age": }}''' Def mapJson = ["Student": ["Name": "","Age": ]] I Need Output as Org. Json. Simple. Jsonobject 2 2...
def stringJson = '''{"Student": {"Name": "","age":}}'''
def mapJson = ["Student": ["Name": "","age": ]]
I need output as org.json.simple.JSONObject
2 Answers
You can parse json string to map and then create org.json.simple.JSONObject instance from this map:
//org.json.simple.JSONObject dependency
@Grapes(
@Grab(group='com.googlecode.json-simple', module='json-simple', version='1.1')
)
import groovy.json.JsonSlurper
import org.json.simple.JSONObject
def stringJson = '''{"Student": {"Name": "","age": null}}'''
//parse json string to map
Map json = new JsonSlurper().parseText(stringJson)
//build JSONObject instance from map
JSONObject jsonObject = new JSONObject(json)
Here is my answer.
import org.json.simple.JSONObject
import groovy.json.JsonSlurper
def stringJson = '''{"Student": {"Name": "","age":""}}'''
def resultJson =new JsonSlurper().parseText(stringJson)
JSONObject jsonObject = new JSONObject(resultJson)
println jsonObject