22

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.9k27 gold badges123 silver badges225 bronze badges
asked Jun 10, 2015 at 13:00
4
  • 3
    "But no success" doesn't tell us any information about the failure mode. What's the value of value? What happens with the code you've tried? Commented Jun 10, 2015 at 13:07
  • Is "savepos" properly formatted JSON and !null? Commented Jun 10, 2015 at 13:10
  • how to convert from Java object ( Sample s = new Sample()) to JSON string? Commented Oct 24, 2017 at 10:10
  • stackoverflow.com/questions/5245840/… Commented Dec 4, 2019 at 12:11

4 Answers 4

68

Try this:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
Seki
11.5k7 gold badges50 silver badges75 bronze badges
answered Jun 10, 2015 at 13:07
Sign up to request clarification or add additional context in comments.

5 Comments

Since There are Multiple JSONParser libraries, Library name would be helpful
how to convert from Java object ( Sample s = new Sample()) to JSON string?
here json.simple Parser is used, I guess.
@MenukaIshan You can import json-simple's parser from org.json.simple.parser.JSONParser
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...
7
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(value);

should do the work.

answered Jun 10, 2015 at 13:08

Comments

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;
}
answered Dec 4, 2019 at 12:13

Comments

-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

answered Jan 6, 2021 at 19:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.