This library intends to make JSON very easy to interact with in Java; it also makes (de)serialization painless.
It wraps around the well-knownorg.json
classes (JSONObject
,JSONArray
,etc.) which also happen to be included
in the Android SDK. As we all know, those stock classes tend to be a pain. They feel bulky, and make you try/catch
waytoo many Exceptions.
- Dependency
- Parsing and Building Objects
- Retrieving Values from Objects
- Parsing and Building Arrays
- Pretty Print
- Paths
- Serialization
- Deserialization
- Annotations
- Retrofit
The dependency is available via jCenter.
dependencies{
...
compile'com.afollestad:ason:[latest-version]'
}
Since Android includesorg.json
classes, you'll want to exclude the copies provided by this library:
dependencies{
...
compile('com.afollestad:ason:[latest-version]') {
excludegroup:'org.json',module:'json'
}
}
In Kotlin, you'll want to exclude IntelliJ's annotations library to avoid a DexException.If you are using Kotlin with Android, make sure you also exclude org.json as shown in the section above.
dependencies{
...
compile('com.afollestad:ason:[latest-version]') {
excludegroup:'com.intellij',module:'annotations'
}
}
<dependency>
<groupId>com.afollestad</groupId>
<artifactId>ason</artifactId>
<version>[latest-version]</version>
<type>pom</type>
</dependency>
There are various ways that this library allows you to construct JSON objects...
Parsing strings is the first, just use the constructor which accepts aString
:
Stringinput=//...
Asonason=newAson(input);
Second, you can build objects using Java fields:
// Translates to { "id":1, "name": "Aidan", "born":1995}
Asonason=newAson() {
intid=1;
Stringname="Aidan";
intborn=1995;
};
Third, you can add values with theput()
method:
Asonason=newAson()
.put("_id",1)
.put("name","Aidan")
.put("born",1995);
You can quickly put in arrays just by passing multiple values toput()
:
// Translates to { "greetings":[ "Hello", "World" ]}
Asonason=newAson();
// The first parameter is a key, you can pass any type for the rest of the varargs parameters
ason.put("greetings","Hello","World");
Various methods exist for retrieving existing values (default values are returned if they don't exist). The one parameter version uses whatever the usual default of a type is (0 for number types, null for everything else), if the no value is found for the key. The two parameter version lets you specify a custom default.
Asonason=//...
Stringstr=ason.getString("name");
StringstrWithDefault=ason.getString("name",null);
Characterchr=ason.getChar("name");
CharacterchrWithDefault=ason.getChar("name",null);
booleanbool=ason.getBool("name");
booleanboolWithDefault=ason.getBool("name",true);
shortshrt=ason.getShort("name");
shortshrtWithDefault=ason.getShort("name",(short)0);
intinteger=ason.getInt("name");
intintegerWithDefault=ason.getInt("name",0);
longlng=ason.getLong("name");
longlngWithDefault=ason.getLong("name",0L);
floatflt=ason.getFloat("name");
floatfltWithDefault=ason.getFloat("name",0f);
doubledoub=ason.getDouble("name");
doubledoubWithDefault=ason.getDouble("name",0d);
bytebyt=ason.getByte("name");
bytebytWithDefault=ason.getByte("name",0d);
Asonobj=ason.getAsonObject("name");
AsonArrayary=ason.getAsonArray("name");
Further, theget(String)
method will actually automatically cast its return value to whatever variable you're setting it to:
Stringstr=ason.get("name");
longlng=ason.get("name");
It will also infer its type if you pass a default value, removing the need to use explicitget[Type]
methods:
if(ason.get("name",false)) {
// do something
}
You can check if values exist, are null, equal another value, or even remove them by key:
Asonason=//...
booleanexists=ason.has("name");
booleanisNull=ason.isNull("name");
booleanvalueEqual=ason.equal("key-name",value);
ason.remove("name");
Like objects, you can parse arrays from Strings:
Stringinput=//...
AsonArray<Ason>array=newAsonArray<Ason>(input);
You can add new objects with.add()
:
AsonArray<String>array=newAsonArray<String>();
// You can add multiple items with a single.put() call, you could use multiple if necessary too
array.add("Hello","World!");
You can retrieve and remove objects by index:
AsonArray<Ason>array=//...
AsonfirstItem=array.get(0);
array.remove(0);
Some other utility methods exist, also:
AsonArray<String>array=//...
intsize=array.size();
booleanempty=array.isEmpty();
booleanitemEqual=array.equal(0,"Does index 0 equal this value?")
Objects and arrays can both be converted to strings simply with thetoString()
method:
Asonason=//...
Stringvalue=ason.toString();// all on one line, no formatting
Stringformatted=ason.toString(4);// 4 spaces being the indent size
Paths use periods and dollar signs to let you quickly add, retrieve, or remove items which are deeper down in your JSON hierarchy without manually traversing.
Lets create an object using a few dot notation keys:
Asonason=newAson()
.put("id",1)
.put("name","Aidan")
.put("birthday.month","July")
.put("birthday.day",28)
.put("birthday.year",1995);
The above would construct this:
{
"id":1,
"name":"Aidan",
"birthday":{
"month":"July",
"day":28,
"year":1995
}
}
As you can see, a child object is automatically created for you. We only use two levels, but you could create many more just by using more periods to separate child names.
You can retrieve values from objects using dot notation:
Asonason=//...
Stringname=ason.get("name");
Stringmonth=ason.get("birthday.month");
intday=ason.get("birthday.day");
intyear=ason.get("birthday.year");
If you wanted to remove the inner "year" value:
Asonason=//...
ason.remove("birthday.year");
You can use dot notation with arrays too, but you need to specify the index of the object to pull from:
AsonArrayason=//...
Stringname=ason.get(1,"birthday.month");
As a bonus, you can check equality without doing a manual value comparison:
Asonason=//...
booleanbirthYearCheck=ason.equal("birthday.year",1995);
AsonArrayason2=//...
booleanbirthYearCheck2=ason2.equal(2,"birthday.year",1995);
To extend on dot notations in paths, you can use this notation to perform operations on array children.
Take this JSON:
{
"group_id":1,
"title":"Hello, world!",
"participants":[
{
"name":"Aidan",
"id":2
},
{
"name":"Nina",
"id":1
}
]
}
You could create this using index notation as such:
Asonason=newAson()
.put("group_id",1)
.put("title","Hello, world!")
.put("participants.$0.name","Aidan")
.put("participants.$0.id",2)
.put("participants.$1.name","Nina")
.put("participants.$1.id",1);
The dollar sign followed by the number 0 indicates that you want the item at index 0 (position 1) within an array called "participants".
You can retrieve the value of "name" in the second participant like this:
Asonobject=//...
Stringname=object.get("participants.$1.name");
If you wanted to remove the first item from the inner array, you can do that with index notation. This avoids the need to first retrieve the "participants" object:
Asonobject=//...
object.remove("participants.$0");
If your keys have literal periods in them, you can escape the periods so that they aren't used when following a path.
Take this JSON:
{
"files":{
"test.txt":"Hello, world!"
}
}
You can retrieve the value if the innertest.txt
string like this:
Asonason=//...
Stringvalue=ason.get("files.test\\.txt ");
We use two forward slashes since Java requires that you escape slashes. The literal string is just"files.test.txt".
You can also escape dollar signs which are normally used with index notation.
Take this JSON:
{
"participants":{
"$1":{
"name":"Nina"
}
}
}
To retrieve the inner string called "name":
Asonason=//...
Stringvalue=ason.get("participants.\\$1.name ");
We use an escaped forward slash (\) in front of the dollar sign to indicate that the dollar sign is literal, and actually used in the name of a key.
This library allows very easy serialization and deserialization. Serialization is converting a Java class instance to JSON.
Take this class for the coming set of examples:
publicclassPerson{
publicintid;
publicStringname;
publicPersonspouse;
publicPerson(intid,Stringname) {
this.id=id;
this.name=name;
}
}
We can serialize an instance as follows:
Personaidan=newPerson(1,"Aidan");
aidan.spouse=newPerson(2,"Nina");
Asonason=Ason.serialize(aidan);
The resultingAson
object is:
{
"id":1,
"name":"Aidan",
"spouse":{
"id":2,
"name":"Nina"
}
}
Serializing arrays is very similar to serializing objects, it uses theserializeArray
method:
Person[]people=//...
AsonArray<Person>array=Ason.serializeArray(people);
Don't forget, you can serialize primitive arrays:
int[]ids=newint[] {1,2,3,4};
AsonArray<Integer>array=Ason.serializeArray(ids);
Serializing lists uses theserializeList
method:
List<Person>people2=//...
AsonArray<Person>array2=AsonArray.serializeList(people2);
If you already have aAson
instance, you can add Java class instances into the object and serialize them automatically:
Asonason=newAson();
Personperson1=newPerson(1,"Aidan");
Personperson2=newPerson(2,"Nina");
ason.put("person1",person);
ason.put("person2",person2);
This would result in:
{
"person1":{
"id":1,
"name":"Aidan"
},
"person2":{
"id":2,
"name":"Nina"
}
}
This automatic serialization works withAsonArray
's too:
AsonArray<Person>array=newAsonArray<Person>();
Personperson1=newPerson(1,"Aidan");
Personperson2=newPerson(2,"Nina");
array.add(person1,person2);
This would result in:
[
{
"id":1,
"name":"Aidan"
},
{
"id":2,
"name":"Nina"
}
]
This library allows very easy serialization and deserialization. Deserialization is converting JSON to a Java class instance.
Again, take this class for the coming set of examples:
publicclassPerson{
publicintid;
publicStringname;
publicPersonspouse;
publicPerson(intid,Stringname) {
this.id=id;
this.name=name;
}
}
We can deserialize an object as follows:
Stringinput="{\ "id\ ":1,\ "name\ ":\ "Aidan\ ",\ "spouse\ ":{\ "id\ ":2,\ "name\ ":\ "Nina\ "}} ";
Asonason=newAson(input);
Personperson=ason.deserialize(Person.class);
There is also a static method which has the same effect:
Stringinput="{\ "id\ ":1,\ "name\ ":\ "Aidan\ ",\ "spouse\ ":{\ "id\ ":2,\ "name\ ":\ "Nina\ "}} ";
Asonason=newAson(input);
Personperson=Ason.deserialize(ason,Person.class);
Lastly, you can directly deserialize JSON strings:
Stringinput="{\ "id\ ":1,\ "name\ ":\ "Aidan\ ",\ "spouse\ ":{\ "id\ ":2,\ "name\ ":\ "Nina\ "}} ";
Personperson=Ason.deserialize(input,Person.class);
You can deserialize JSON arrays to Java lists and arrays too:
Stringinput="[{\ "name\ ":\ "Aidan\ ",\ "_id\ ":1},{\ "name\ ":\ "Nina\ ",\ "_id\ ":2}] ";
AsonArray<Person>array=newAsonArray<>(input);
Person[]peopleArray=array.deserialize(Person[].class);
There is also static methods which have the same effect:
Stringinput="[{\ "name\ ":\ "Aidan\ ",\ "_id\ ":1},{\ "name\ ":\ "Nina\ ",\ "_id\ ":2}] ";
AsonArray<Person>array=newAsonArray<>(input);
Person[]peopleArray=Ason.deserialize(array,Person[].class);
Lastly, you can directly deserialize JSON strings:
Stringinput="[{\ "name\ ":\ "Aidan\ ",\ "_id\ ":1},{\ "name\ ":\ "Nina\ ",\ "_id\ ":2}] ";
Person[]peopleArray=Ason.deserialize(input,Person[].class);
One more thing, you can deserialize arrays containing primitive types:
Stringinput="[1,2,3,4]";
int[]primitiveArray=Ason.deserialize(input,int[].class);
Unlike objects and arrays, deserializing lists requires a separate method:
Stringinput="[{\ "name\ ":\ "Aidan\ ",\ "_id\ ":1},{\ "name\ ":\ "Nina\ ",\ "_id\ ":2}] ";
AsonArray<Person>array=newAsonArray<>(input);
List<Person>peopleList=array.deserializeList(Person.class);
There is also a static method which has the same effect:
Stringinput="[{\ "name\ ":\ "Aidan\ ",\ "_id\ ":1},{\ "name\ ":\ "Nina\ ",\ "_id\ ":2}] ";
AsonArray<Person>array=newAsonArray<>(input);
List<Person>peopleList=Ason.deserializeList(array,Person.class);
You can deserialize strings directly:
Stringinput="[{\ "name\ ":\ "Aidan\ ",\ "_id\ ":1},{\ "name\ ":\ "Nina\ ",\ "_id\ ":2}] ";
List<Person>peopleList=Ason.deserializeList(input,Person.class);
If you already have aAson
instance, you can automatically pull out and deserialize Java class instances without
using theAsonSerializer
directly:
Asonason=//...
// The JSON object needs to contain a child object with the key "person" representing the Person class.
Personperson=ason.get("person",Person.class);
The same works forAsonArray
's:
AsonArray<Person>array=//...
// The JSON array needs to contain a list of objects representing the Person class.
Personperson=array.get(0,Person.class);
For Lists, you need to use a separate method since it requires that you specific the type held by the list:
Asonason=//...
// The JSON object needs to contain a child array with the key "people" representing an array of Person classes.
List<Person>people=array.getList("people",Person.class);
This library comes with a two annotations that have their own special use cases.
This annotation allows you to assign a custom name to fields.
It's used withAson
field construction:
Asonason=newAson() {
@AsonName(name="_id")intid=1;
Stringname="Aidan";
intborn=1995;
};
And of course during serialization and deserialization:
publicclassPerson{
@AsonName(name="_id")intid;
Stringname;
intborn;
publicPerson(intid,Stringname,intborn) {
this.id=id;
this.name=name;
this.born=born;
}
}
This annotation tells the library to ignore and fields it's used to mark. That means the field is not serialized, deserialized, or used with field construction:
publicclassPerson{
@AsonIgnoreStringinvisibleField="Hello, world!";
intid;
Stringname;
intborn;
publicPerson(intid,Stringname,intborn) {
this.id=id;
this.name=name;
this.born=born;
}
}
Ason's built in Retrofit converters let you send and receive objects with Retrofit, they are automatically serialized or deserialized. Just add the converter factory to your Retrofit instances:
Retrofitretrofit=
newRetrofit.Builder()
...
.addConverterFactory(newAsonConverterFactory())
.build();
AsonConverterFactory
exists in a separate dependency:
dependencies{
...
compile'com.afollestad:ason-retrofit:[latest-version]'
}