Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Building Better JSON blog post companion code.
...
/*
* the main data object, we've read the API docs and know what to expect ;-)
* assuming that the previously output JSON data is what we're pulling off of
*/
class SomeNiftyDataObject {
private String hello;
private List<SomeNiftySubObject> dataAr = new ArrayList<SomeNiftySubObject>();
private boolean error;
/*
* the sub-object, in the dataAr
* since we need to define the sub-object's
* structure as well
*/
class SomeNiftySubObject {
private String _id;
private String someOtherKey;
/*
* Getter / Setter pairs
*/
public String get_id() { return _id; }
public String getSomeOtherKey() { return someOtherKey; }
public void set_id( String id ) { this._id = id; }
public void setSomeOtherKey( String someOtherKey ) { this.someOtherKey = someOtherKey; }
}
/*
* Getter / Setter pairs
*/
public String getHello() { return hello; }
public List<SomeNiftySubObject> getDataAr() { return dataAr; }
public boolean getError() { return error; }
public void setHello( String hello ) { this.hello = hello; }
public void setDataAr( List<SomeNiftySubObject> dataAr ) { this.dataAr = dataAr; }
public void setError( boolean error ) { this.error = error; }
}
...
/*
* we're building data, from a received set of JSON, into
* a Java object, so we can do normal Java things with it
*/
private void buildMyNewJsonData () {
// assuming that the JSON of the data is set in a string called rawData
Gson g = new Gson();
SomeNiftyDataObject nwData = g.fromJson( rawData, SomeNiftyDataObject.class );
//SomeNiftyDataObject is now instantiated with the data set according to our class above!
}
...
...
private void buildJsonData() {
JsonJavaObject myData = new JsonJavaObject();
myData.putJsonProperty("hello", "world");
JsonJavaArray dataAr = new JsonJavaArray();
for( int i=0; i<5; i++ ) {
JsonJavaObject subObject = new JsonJavaObject();
subObject.putJsonProperty("_id",i+1);
subObject.putJsonProperty("someOtherKey", "someOtherValue");
}
myData.putArray("data", dataAr);
myData.putJsonProperty("error", false);
}
...
{
"hello": "world",
"dataAr": [
{ "_id": 1, "someOtherKey": "someOtherValue" },
{ "_id": 2, "someOtherKey": "someOtherValue" },
{ "_id": 3, "someOtherKey": "someOtherValue" },
{ "_id": 4, "someOtherKey": "someOtherValue" },
{ "_id": 5, "someOtherKey": "someOtherValue" }
],
"error": false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment