Last active
September 13, 2022 13:17
-
-
Save hrchu/4f8a4e5da2d2ec69cfb1f121f27369a8 to your computer and use it in GitHub Desktop.
Convert Json from/to object/tree/inputstream/reader/file with Gson in Java
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
import com.google.gson.Gson; | |
import com.google.gson.JsonElement; | |
import java.io.ByteArrayInputStream; | |
import java.io.InputStreamReader; | |
import org.junit.jupiter.api.Test; | |
/** | |
* Convert Json from/to object/tree/inputstream/reader/file with Gson in Java | |
* | |
* ref https://www.javadoc.io/doc/com.google.code.gson/gson/2.9.0/com.google.gson/com/google/gson/Gson.html | |
* | |
*/ | |
class BagOfPrimitives { | |
private int value1 = 1; | |
private String value2 = "abc"; | |
private transient int value3 = 3; | |
BagOfPrimitives() { | |
// no-args constructor | |
} | |
@Override | |
public String toString() { | |
return "BagOfPrimitives{" + | |
"value1=" + value1 + | |
", value2='" + value2 + '\'' + | |
", value3=" + value3 + | |
'}'; | |
} | |
} | |
public class TestGson { | |
@Test | |
void serialize() { | |
// obj to str | |
BagOfPrimitives obj = new BagOfPrimitives(); | |
Gson gson = new Gson(); | |
String json = gson.toJson(obj); | |
System.out.println(json); | |
} | |
@Test | |
void deserialize() { | |
Gson gson = new Gson(); | |
BagOfPrimitives obj; | |
// str to obj | |
obj = gson.fromJson("{\"value1\":1,\"value2\":\"abc\"}", BagOfPrimitives.class); | |
System.out.println(obj); | |
// reader (inputstream/file) to obj | |
// InputStream is = TestGson.class.getResourceAsStream("/xxx.json") | |
InputStream is = new ByteArrayInputStream( | |
"{\"value1\":1,\"value2\":\"abc\"}".getBytes()); | |
obj = gson.fromJson(new InputStreamReader(is), BagOfPrimitives.class); | |
System.out.println(obj); | |
} | |
/** | |
* JsonElement is a map/tree like data structure. | |
* | |
* JsonElement | |
* / \ | |
* / Gson \ | |
* / \ | |
* Json doc ---- Object | |
* | |
**/ | |
@Test | |
void jsonElement() { | |
BagOfPrimitives obj = new BagOfPrimitives(); | |
Gson gson = new Gson(); | |
// obj to tree | |
JsonElement jsonTree = gson.toJsonTree(obj); | |
System.out.println(jsonTree); | |
// tree to obj | |
obj = gson.fromJson(jsonTree, BagOfPrimitives.class); | |
System.out.println(obj); | |
// tree to str | |
String json = gson.toJson(jsonTree); | |
System.out.println(json); | |
// str to tree | |
jsonTree = gson.fromJson(json, JsonElement.class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment