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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like