-
Notifications
You must be signed in to change notification settings - Fork 7
GSON
Tim L edited this page Oct 30, 2013
·
12 revisions
GSON is a very nice Java library to map JSON into Java objects (and vice versa). Thanks to OKFN's Ross Jones for https://github.com/okfn/CKANClient-J (my fork) and it's eloquent use of GSON. My notes about this are at #sadi-using-java-take-2.
List getDatasetRevisions(String datasetName) uses GSON.
- First, get a JSON string (with GET or POST).
- Next, create an inner class for the response.
When the JSON looks like:
[
{
"uri":"http://dbpedia.org/resource/Edinburgh",
"numDuplicates":"176",
"duplicates": [
"http://dbpedia.org/resource/Eidyn",
"http://dbpedia.org/resource/Embra",
"http://dbpedia.org/resource/Embro",
"http://yago-knowledge.org/resource/Edinburgh",
"http://yago-knowledge.org/resource/Areas_of_Edinburgh",
"http://yago-knowledge.org/resource/Edinburgh_Inspiring_Capital"
]
}
]
use (thanks to stackoverflow):
public class MyClass {
@Override
public void doMyJSONThing() {
String content; // The JSON String.
...
Gson gson = new Gson();
JsonParser jparser = new JsonParser();
for( JsonElement object : jparser.parse(content).getAsJsonArray() ) {
MyClass.URI uri = gson.fromJson(object, MyClass.URI.class);
System.out.println(uri.uri);
for( String duplicate : uri.duplicates ) {
System.out.println(duplicate);
}
}
}
}
/**
* For GSON
*/
public class URI {
public String uri; // The "uri" attribute in the JSON object
public List<String> duplicates; // The "duplicates" attribute in the JSON object
}
}