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?

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);
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.

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.