https://github.com/derlin/gsonutils
A java .jar easing the use of the Gson library.
https://github.com/derlin/gsonutils
Last synced: 8 months ago
JSON representation
A java .jar easing the use of the Gson library.
- Host: GitHub
- URL: https://github.com/derlin/gsonutils
- Owner: derlin
- Created: 2015-06-26T18:33:43.000Z (almost 11 years ago)
- Default Branch: master
- Last Pushed: 2015-12-01T15:37:30.000Z (over 10 years ago)
- Last Synced: 2025-03-13T14:43:39.582Z (about 1 year ago)
- Language: Java
- Size: 513 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# GsonUtils
A java .jar easing the use of the Gson library. The class `GsonUtils` offers static methods to quickly:
* load an object from a json file
* serialize an object into a string
* serialize an object into a file
* exclude fields from the serialization with the `@DoNotSerialize` annotation.
# How to use
Add the jar to the classpath.
To serialize __an object into a file__, you two methods, taking either a path to a file or the file itself. For example,
if you have an object, you can do:
```java
MyObject myObject = new MyObject();
GsonUtils.writeToFile("/path/to/a/file.json", myObject, true);
```
The boolean parameter determines if the output should be prettyprinted or not.
If your object is a collection or another generic object, you can use the `TypeToken` class, like that:
```java
Map map = new HashMap<>();
GsonUtils.writeToFile("/path/to/a/file.json", new TypeToken>(){}, true);
```
To deserialize a __json file to an object__, the principle is the same:
```java
MyObject myObject =v (MyObject) GsonUtils.getFromFile("/path/to/a/file.json", new MyObject());
Map map = (HashMap)
GsonUtils.getFromFile("/path/to/a/file.json", new TypeToken>(){});
```
Finally, you can serialize __an object into a string__. The method `dump` serialize every field, the method `toJson` will
exclude any field annotated with `@DoNotSerialize`.