20

I am using org.json.simple.JSONObject. I want to convert string to Json object.

String value=request.getParameter("savepos");
JSONObject jsonObject = (JSONObject) JSONValue.parse(value);

It doesn't work. Why?

Olivier Pons
  • 15,363
  • 26
  • 117
  • 213
Talib
  • 1,134
  • 5
  • 31
  • 58

4 Answers4

67

Try this:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
Seki
  • 11,135
  • 7
  • 46
  • 70
Shailesh Yadav
  • 1,061
  • 1
  • 15
  • 30
  • 19
    Since There are Multiple JSONParser libraries, Library name would be helpful – Menuka Ishan May 05 '17 at 11:13
  • 2
    how to convert from Java object ( Sample s = new Sample()) to JSON string? – Ghost Rider Oct 24 '17 at 10:10
  • here json.simple Parser is used, I guess. – Mukit09 Sep 01 '19 at 04:31
  • 1
    @MenukaIshan You can import json-simple's parser from `org.json.simple.parser.JSONParser` – ado387 Jul 14 '21 at 11:48
  • 1
    Why are all the examples so limited and incomplete? No import namespace included, the method seems to require a try-catch block, no example how to transfer back to string... Thanks for this idea, but it could be so much more helpful if you simply completed the thought... – barrypicker Sep 12 '21 at 19:27
7
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(value);

should do the work.

Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63
1

Converting String to Json Object by using org.json.simple.JSONObject

private static JSONObject createJSONObject(String jsonString){
    JSONObject  jsonObject=new JSONObject();
    JSONParser jsonParser=new  JSONParser();
    if ((jsonString != null) && !(jsonString.isEmpty())) {
        try {
            jsonObject=(JSONObject) jsonParser.parse(jsonString);
        } catch (org.json.simple.parser.ParseException e) {
            e.printStackTrace();
        }
    }
    return jsonObject;
}
Anzar Ansari
  • 109
  • 1
  • 5
-2

In the newer com.github.cliftonlabs.json_simple the code is the following:

JsonObject obj = Jsoner.deserialize(responseString, new JsonObject());

As documented on the project's API docs

Kartik Chugh
  • 1,104
  • 14
  • 28