In this tutorial, we are going to implement Google's GSON to our Java application. First, you need to create a simple class that JSON data can represent:
import java.util.ArrayList; import java.util.List; public class MyData{ public String message = "Hello, World!"; private ListIt represents our JSON data. So now we want to convert this object into JSON format. How should we do that? Please copy & paste the example below:messages = new ArrayList (){ { add("Message for friends"); add("Message for family"); add("Message for girlfriends"); add("Message for strangers"); } }; public String toString(){ return "MyData[message=" + message + ", messages=" + messages + "]"; } }
import java.io.FileWriter; import java.io.IOException; import com.google.gson.Gson; public class Main { public static void main(String[] args) { MyData obj = new MyData(); Gson gson = new Gson(); String json = gson.toJson(obj); try { FileWriter writer = new FileWriter("C:\\data.json"); writer.write(json); writer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("JSON:" + json); } }The trick here is to call the Gson class' toJson method. It will going to return the JSON encoded object as String. Very handy! Now the next lines are just the method to save it to a file called "data.json". Do not forget to close your resources to free up some memories.
Now that you have already your json file, you probably want it to send over the network. You need now to convert the JSON encoded format back to a simple java object. Here's the code for that:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import com.google.gson.Gson; public class Main { public static void main(String[] args) { Gson gson = new Gson(); try { BufferedReader br = new BufferedReader( new FileReader("C:\\data.json")); MyData data = gson.fromJson(br, MyData.class); System.out.println(data); } catch (IOException e) { e.printStackTrace(); } } }
Play around this wonderful library by Google and I'm sure in one day you will get the hang of it! Easy right?
Thanks for reading all my stuff here in Geek Stuff!