Created
July 19, 2016 13:17
-
-
Save sunmeat/5f7e38e0393ad3a8fd29b0eb761cb873 to your computer and use it in GitHub Desktop.
simple gson example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package serialization; | |
import com.google.gson.Gson; | |
import java.io.*; | |
class Program { | |
public static void main(String[] args) throws FileNotFoundException, IOException { | |
Gson gson = new Gson(); | |
gson.toJson(1); | |
gson.toJson("abcd"); | |
gson.toJson(new Long(10)); | |
int[] values = {1, 2, 3, 4, 5}; | |
String s = gson.toJson(values); | |
System.out.println(s); | |
int a = gson.fromJson("1", int.class); | |
Integer b = gson.fromJson("1", Integer.class); | |
Long c = gson.fromJson("1", Long.class); | |
Boolean d = gson.fromJson("false", Boolean.class); | |
String e = gson.fromJson("\"abc\"", String.class); | |
String path = "C:\\1\\1.txt"; | |
FileOutputStream outputStream; | |
try { | |
outputStream = new FileOutputStream(path); | |
outputStream.write(s.getBytes()); | |
outputStream.close(); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
FileInputStream fis = new FileInputStream(path); | |
InputStreamReader isr = new InputStreamReader(fis); | |
BufferedReader bufferedReader = new BufferedReader(isr); | |
StringBuilder sb = new StringBuilder(); | |
String line; | |
while ((line = bufferedReader.readLine()) != null) { | |
sb.append(line); | |
} | |
String json = sb.toString(); | |
System.out.println(json); | |
gson = new Gson(); | |
int[] result = gson.fromJson(json, int[].class); | |
System.out.println(result[2]); | |
Runtime r = Runtime.getRuntime(); | |
r.exec("cmd /c " + path); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment