I have String variable called jsonString
:
{"phonetype":"N95","cat":"WP"}
Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers...
I have String variable called jsonString
:
{"phonetype":"N95","cat":"WP"}
Now I want to convert it into JSON Object. I searched more on Google but didn't get any expected answers...
I like to use google-gson for this, and it's precisely because I don't need to work with JSONObject directly.
In that case I'd have a class that will correspond to the properties of your JSON Object
However, I think your question is more like, How do I endup with an actual JSONObject object from a JSON String.
I was looking at the google-json api and couldn't find anything as straight forward as org.json's api which is probably what you want to be using if you're so strongly in need of using a barebones JSONObject.
http://www.json.org/javadoc/org/json/JSONObject.html
With org.json.JSONObject (another completely different API) If you want to do something like...
I think the beauty of google-gson is that you don't need to deal with JSONObject. You just grab json, pass the class to want to deserialize into, and your class attributes will be matched to the JSON, but then again, everyone has their own requirements, maybe you can't afford the luxury to have pre-mapped classes on the deserializing side because things might be too dynamic on the JSON Generating side. In that case just use json.org.
NOTE that GSON with deserializing an interface will result in exception like below.
While deserialize; GSON don't know which object has to be intantiated for that interface.
This is resolved somehow here.
However FlexJSON has this solution inherently. while serialize time it is adding class name as part of json like below.
So JSON will be cumber some; but you don't need write
InstanceCreator
which is required in GSON.Better Go with more simpler way by using
org.json
lib. Just do a very simple approach as below:Now
obj
is your convertedJSONObject
form of your respective String. This is in case if you have name-value pairs.For a string you can directly pass to the constructor of
JSONObject
. If it'll be a validjson String
, then okay otherwise it'll throw an exception.There are various Java JSON serializers and deserializers linked from the JSON home page.
As of this writing, there are these 20:
...but of course the list can change.
To convert
String
intoJSONObject
you just need to pass theString
instance into Constructor ofJSONObject
.Eg:
No need to use any external library.
You can use this class instead :) (handles even lists , nested lists and json)
To convert your JSON string to hashmap use this :