2017年4月29日 星期六

[ Java 文章收集 ] How to convert Java object to / from JSON (Gson)

Source From Here
Preface
In this tutorial, we will show you how to use Gson to convert Java object to / from JSON. Below is the basic description of Gson:
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Note.
JSON stands for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many Java applications started to throw away XML format and start using JSON as a new data-interchange format. Java is all about object, often times, you need to convert an object into JSON format for data-interchange or vice verse.

Jackson is another high performance JSON processor, try this Jackson 2 – Java object to / from JSON

1. Quick Reference

1.1 toJson() – Convert Java object to JSON
  1. package demo.gson;  
  2.   
  3. import java.io.FileWriter;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import com.google.gson.Gson;  
  8.   
  9. public class People {  
  10.     public String       name = null;  
  11.     public int          age = 0;  
  12.     public List   addr = new ArrayList();  
  13.     public boolean      isSingle=false;  
  14.   
  15.     @Override  
  16.     public String toString()  
  17.     {  
  18.         StringBuffer strBuf = new StringBuffer(String.format("Name: %s\n", name));  
  19.         strBuf.append(String.format("Age: %d\n", age));  
  20.         strBuf.append(String.format("IsSingle? %s\n", isSingle));  
  21.         strBuf.append("Addr:\n");  
  22.         for(String a:addr) strBuf.append(String.format("\t%s\n", a));  
  23.         return strBuf.toString();  
  24.     }  
  25.       
  26.     public static void ToJson() throws Exception  
  27.     {  
  28.         People p = new People();  
  29.         p.name = "John"; p.age = 36; p.addr.add("abc"); p.addr.add("123"); p.isSingle=true;  
  30.         Gson gson = new Gson();  
  31.           
  32.         // 1. Java object to JSON, and save into a file  
  33.         FileWriter fw = new FileWriter("john.json");  
  34.         gson.toJson(p, fw);  
  35.         fw.flush(); fw.close();  
  36.   
  37.         // 2. Java object to JSON, and assign to a String  
  38.         String jsonInString = gson.toJson(p);  
  39.         System.out.printf("%s\n", jsonInString);  
  40.     }  
  41. }  
Output:
{"name":"John","age":36,"addr":["abc","123"],"isSingle":true}

1.2 fromJson() – Convert JSON to Java object
  1. public static void FromJson() throws Exception{  
  2.     Gson gson = new Gson();  
  3.   
  4.     // 1. JSON to Java object, read it from a file.  
  5.     FileReader fw = new FileReader("john.json");  
  6.     People p1 = gson.fromJson(fw, People.class);  
  7.     System.out.printf("P1:\n%s\n", p1);  
  8.     fw.close();  
  9.   
  10.     // 2. JSON to Java object, read it from a Json String.  
  11.     String jsonInString = "{'name':'John','age':36,'addr':['abc','123'],'isSingle':true}";  
  12.     People p2 = gson.fromJson(jsonInString, People.class);  
  13.     System.out.printf("P2:\n%s\n", p2);  
  14.   
  15.     // JSON to JsonElement, convert to String later.  
  16.     JsonElement json = gson.fromJson(new FileReader("john.json"), JsonElement.class);  
  17.     String result = gson.toJson(json);  
  18.     System.out.printf("P3:\n%s\n", result);  
  19. }  
2. FAQs
Some commonly ask questions.

2.1 Convert a JSON Array to a List, using TypeToken
  1. package demo.gson;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.google.gson.Gson;  
  6. import com.google.gson.reflect.TypeToken;  
  7.   
  8. public class Movie {  
  9.     public String   name = "";  
  10.     public int      cost = 0;  
  11.     public Movie(String n, int c){this.name = n; this.cost = c;}  
  12.       
  13.     @Override  
  14.     public String toString()  
  15.     {  
  16.         return String.format("%s/%d", name, cost);  
  17.     }  
  18.       
  19.     public static void main(String args[])  
  20.     {  
  21.         String json = "[{\"name\":\"Scary Movie\",\"cost\":50}, {\"name\":\"Action Movie\",\"cost\":50}]";  
  22.         Gson gson = new Gson();  
  23.         List list = gson.fromJson(json, new TypeToken>(){}.getType());  
  24.         for(Movie m:list) {System.out.printf("%s\n", m);}  
  25.     }  
  26. }  
Output:
Scary Movie/50
Action Movie/50

2.2 Convert a JSON to a Map
  1. public static void CovJson2Map()  
  2. {  
  3.     String json = "{\"name\":\"Comedy Movie\",\"cost\":30}";  
  4.     Gson gson = new Gson();  
  5.     Map map = gson.fromJson(json, new TypeToken>(){}.getType());  
  6.     map.forEach((x,y)->System.out.printf("%s|%s\n", x, y));  
  7. }  
Output:
name|Comedy Movie
cost|30.0

2.3 Enable JSON pretty print feature in Gson
1. By default, Gson display the JSON output like the following :
  1. Gson gson = new Gson();  
  2. People p = new People();  
  3. p.name = "John"; p.age = 36; p.addr.add("abc"); p.addr.add("123"); p.isSingle=true;  
  4. String json = gson.toJson(p);  
  5. System.out.println(json);  
Output:
{"name":"John","age":36,"addr":["abc","123"],"isSingle":true}

2. To enable the pretty-print, create the Gson object with GsonBuilder
  1. Gson gson = new GsonBuilder().setPrettyPrinting().create();  
  2. People p = new People();  
  3. p.name = "John"; p.age = 36; p.addr.add("abc"); p.addr.add("123"); p.isSingle=true;  
  4. String json = gson.toJson(p);  
  5. System.out.println(json);  
Output:
  1. {  
  2.   "name""John",  
  3.   "age"36,  
  4.   "addr": [  
  5.     "abc",  
  6.     "123"  
  7.   ],  
  8.   "isSingle"true  
  9. }  

2 則留言:

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...