Skip to content
This repository has been archived by the owner on Jun 16, 2019. It is now read-only.
/ ason Public archive

[DEPRECATED]: Prefer Moshi, Jackson, Gson, or LoganSquare

License

Notifications You must be signed in to change notification settings

afollestad/ason

Repository files navigation

Ason

Download Build Status Codecov Codacy Badge License

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.jsonclasses (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.


Table of Contents

  1. Dependency
    1. Gradle (Java)
    2. Gradle (Android)
    3. Gradle (Kotlin)
    4. Maven
  2. Parsing and Building Objects
  3. Retrieving Values from Objects
  4. Parsing and Building Arrays
  5. Pretty Print
  6. Paths
    1. Dot Notation
    2. Index Notation
    3. Escaping Periods and Dollar Signs
  7. Serialization
    1. Serializing Objects
    2. Serializing Arrays
    3. Serializing Lists
    4. Automatic Serialization
  8. Deserialization
    1. Deserializing Objects
    2. Deserializing Arrays
    3. Deserializing Lists
    4. Automatic Deserialization
  9. Annotations
    1. @AsonName
    2. @AsonIgnore
  10. Retrofit

Dependency

The dependency is available via jCenter.

Gradle (Java)

dependencies{
...
compile'com.afollestad:ason:[latest-version]'
}

Gradle (Android)

Since Android includesorg.jsonclasses, you'll want to exclude the copies provided by this library:

dependencies{
...
compile('com.afollestad:ason:[latest-version]') {
excludegroup:'org.json',module:'json'
}
}

Gradle (Kotlin)

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'
}
}

Maven

<dependency>
<groupId>com.afollestad</groupId>
<artifactId>ason</artifactId>
<version>[latest-version]</version>
<type>pom</type>
</dependency>

Parsing and Building Objects

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");

Retrieving Values from Objects

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");

Parsing and Building Arrays

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?")

Pretty Print

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

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.

Dot Notation

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);

Index Notation

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");

Escaping Periods and Dollar Signs

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.txtstring 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.


Serialization

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;
}
}

Serializing Objects

We can serialize an instance as follows:

Personaidan=newPerson(1,"Aidan");
aidan.spouse=newPerson(2,"Nina");

Asonason=Ason.serialize(aidan);

The resultingAsonobject is:

{
"id":1,
"name":"Aidan",
"spouse":{
"id":2,
"name":"Nina"
}
}

Serializing Arrays

Serializing arrays is very similar to serializing objects, it uses theserializeArraymethod:

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

Serializing lists uses theserializeListmethod:

List<Person>people2=//...
AsonArray<Person>array2=AsonArray.serializeList(people2);

Automatic Serialization

If you already have aAsoninstance, 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"
}
]

Deserialization

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;
}
}

Deserializing Objects

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);

Deserializing Arrays

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);

Deserializing Lists

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);

Automatic Deserialization

If you already have aAsoninstance, you can automatically pull out and deserialize Java class instances without using theAsonSerializerdirectly:

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);

Annotations

This library comes with a two annotations that have their own special use cases.

@AsonName

This annotation allows you to assign a custom name to fields.

It's used withAsonfield 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;
}
}

@AsonIgnore

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;
}
}

Retrofit

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();

AsonConverterFactoryexists in a separate dependency:

dependencies{
...
compile'com.afollestad:ason-retrofit:[latest-version]'
}