Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JSONObject from String

How can I get a JSONObject from a HttpServletRequest in servlets?

like image 850
Anil Bharadia Avatar asked Aug 05 '10 11:08

Anil Bharadia


People also ask

How do I convert a String to a JSON object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

How do you parse a JSON object in Java?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

What does JSON object get do?

A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods.


2 Answers

Very simple:

JSONObject o = new JSONObject(request.getParameter("WHATEVER"));

Edit: Since you use json-lib, it's

JSONObject o = (JSONObject) JSONSerializer.toJSON(request.getParameter("WHATEVER"));  

for you.

like image 73
Erich Kitzmueller Avatar answered Oct 17 '22 07:10

Erich Kitzmueller


It seems like you must be using the net.sf.json.JSONObject version of JSONObject (this is not the json.org version).

For the net.sf.json.JSONObject version simply use

JSONObject.fromObject(Object obj)

where obj is either

  • a valid JSON formatted string
  • a Bean POJO with getters and setters.
like image 34
cyber-monk Avatar answered Oct 17 '22 08:10

cyber-monk