Here's an example that shows how to play around with JSON objects in java. There are a bunch of JSON libraries. This example users json.org.
checkout the code here
checkout the code here
package org.megha.blog.example.json; |
import org.json.JSONArray; |
import org.json.JSONObject; |
/** |
* Play around with {@code json.org}'s JSON library. |
* To run this, you import the library from json.org. |
* |
* @author megha birmiwal |
*/ |
public class JsonPrinter { |
public static void main(String[] args) { |
// create a json object from a json string |
String responseData =
"{'name':'Robert','interests':['Swimming','Music',123]," |
+ "'address':{'city': 'Bangalore'}}"; |
JSONObject jsonObject = new JSONObject(responseData); |
// convert back to "pretty-printed" string |
System.out.println(jsonObject.toString(4)); |
// extract values from a json object |
String name = jsonObject.getString("name"); |
System.out.println(name); |
JSONArray jsonArray = jsonObject.getJSONArray("interests"); |
System.out.println(jsonArray.toString(2)); |
// json array has .length() and .getXXX(index) methods to get elements |
// also has a .join() to join values into a string with the
// specified separator |
String interests = jsonArray.join(" "); |
System.out.println(interests); |
JSONObject address = jsonObject.getJSONObject("address"); |
String addressCity = address.getString("city"); |
System.out.println(addressCity); |
// adding entries is trivial. just call put() |
address.put("country", "India"); |
// difference between pretty-printed and condensed outputs |
System.out.println(address.toString()); |
System.out.println(address.toString(2)); |
// note that it prints address with the added country |
System.out.println(jsonObject.toString(4)); |
} |
} |
No comments:
Post a Comment