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 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest