-3

I am trying to convert a String to a JSON in Java. I tried Gson and JSONObject.toJson but they are not helping me .

 String str = "{"rahul":"reddy"}";

This is my string , I want this to be converted into a JSON.Can anyone please help me .

Newbie
  • 2,664
  • 7
  • 34
  • 75
  • An example of what you tried and how it failed would be helpful. – crownjewel82 Oct 31 '13 at 18:08
  • possible duplicate of [How to convert String to JSONObject in Java](http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java) – msangel Oct 31 '13 at 18:09
  • You should try escaping the `"`s... `String str = "{\"rahul\":\"reddy\"}";` – jonhopkins Oct 31 '13 at 18:09
  • 1
    What do mean *converter into a JSON*? A valid JSON string? A JSON object (like `org.json.JSONObject`)? – rzymek Oct 31 '13 at 18:10
  • Do you want to see an answer without GSON? I can show you with org.json which is the built in library – meda Oct 31 '13 at 18:11
  • Looks like this is similar to the question posted in below link: http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java – Gayathri Oct 31 '13 at 18:15
  • add those did not help I have already tried – Newbie Oct 31 '13 at 18:18

1 Answers1

1

If you're looking to parse JSON from a string to an object, firstly you'll need to choose a library. An easy choice is json-simple

// note that I have escaped the inner "
String string = "{\"rahul\":\"reddy\"}";
JSONObject json = (JSONObject)new JSONParser().parse(string);

To get values back:

json.get("rahul"); // --> "reddy"
azz
  • 5,852
  • 3
  • 30
  • 58