Reputation: 3920
I have a json response string like this
string result ={"username": "sdrG", "size": 965204, "filename": "test.doc"}
From this am trying to get the size value
for that am using JSON object to convert JSON string get the key values
JSONObject jObject = new JSONObject(result); // json
String size = (String) jObject.get("size");
System.out.println(size);
But his code is not working for me getting
org.json.JSONException: JSONObject["size"] not found.
Upvotes: 1
Views: 550
Reputation: 5649
After a little modification, your code worked for me:-
public static void main(String[] args) throws DatatypeConfigurationException {
String result ="{\"username\": \"sdrG\", \"size\": 965204, \"filename\": \"test.doc\"}";
JSONObject jObject = new JSONObject(result); // json
String size = String.valueOf((Integer) jObject.get("size"));
System.out.println(size);
}
Used :-
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
In case your Json is stored in StringBuffer, you can do:-
JSONObject jObject = new JSONObject(result.toString());
Upvotes: 2
Reputation: 4507
JSONParser parser=new JSONParser();
JSONObject jObject = (JSONObject)parser.parse(result);
String size = (String) jObject.get("size");
System.out.println(size);
Upvotes: 0