I have a Json file like this:
[{
dname: "xxxx",
dage: "24"
}, {
dname: "yyyy",
dage: "26"
}]
Target:
I want to access them as an array
Search through the names in the JSON file to look for a particular name
Same for age.
What I did:
file name : DtExtract.java
public class DtExtract{
public static ObjectMapper mapper = new ObjectMapper();
private Dtmain[] dtmain =mapper.readValue(new File("file location"), TypeFactory.defaultInstance().constructArrayType(D tmain.class));
public DtExtract() throws IOException{}
public String getname(int i) throws IOException { String strname = dtmain[i].getjname(); return strname;}
public String getage(int i) throws IOException { String strage = dtmain[i].getjage(); return strage;}
}
class Dtmain {
private String dname;
private String dage;
public Dtmain(){}
public String getjname(){return dname;}
public String getjage(){return dage;}
public void setjname(String dname){ this.dname=dname;}
public void setjage(String dage){ this.dage=dage;}
public String toString(){ return "Student [ name" + dname +", age " +dage +"]";
}
============================
file name: Myclass.java
public class Myclass{
public static void main(String args[]) throws IOException {
DtExtract dtextract= new DtExtract();
for(int i=0; i< 2; i++)
{
if (dtextract.getname(i).equals("xxxx")) {System.out.print("Name matches");}
if (dtextract.getage(i).equals("24")) {System.out.print("Age matches");}
}
}
}
=============================
This is the abstract of a code that I have, but my question is:
Does this for loop is really accessing the JSON array elements?
Is there any other faster way to do this JSON parsing and comparison?
You can do it as follows. You need to call both methods from main method
Please note that I have added two methods to process the array. processJsonArrayJava8 will be faster compared to processJsonArrayJava7.
public List<Dtmain> readFromJson()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Dtmain>> mapType = new TypeReference<List<Dtmain>>() {};
List<Dtmain> jsonList = mapper.readValue(
"[{\"dname\": \"xxxx\",\"dage\": \"24\" },{\"dname\": \"yyyy\",\"dage\": \"26\" }]",
mapType);
return jsonList;
}
public void processJsonArrayJava7(List<Dtmain> jsonList) {
for(Dtmain obj : jsonList) {
// do what ever you want with obj
}
}
public void processJsonArrayJava8(List<Dtmain> jsonList) {
jsonList.parallelStream().forEach(obj->{
//do what ever you want with obj
});
}
Please also give better names to the methods.
public class SayHi {
public static void main(String args[]) throws IOException {
try {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Person>> maptype = new TypeReference<List<Person>>() {};
List<Person> jsonTopersonList=mapper.readValue(new File("JSON_file_location"), maptype);
for(int i=0; i<jsonTopersonList.size(); i++){
System.out.println("Name"+i+":"+jsonTopersonList.get(i).dname);
}
for(int i=0; i<jsonTopersonList.size(); i++){
System.out.println("Age"+i+":"+jsonTopersonList.get(i).dage);
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class Person {
public String dname;
public int dage;
public Person() {
}
public Person(String dname,
int dage) {
this.dname = dname;
this.dage = dage;
}
public String toString() {
return "[" + dname + " " + dage +"]";
}
}
I came up with this one to deserialize that json data.
Related
I need to convert a JSON response into Java Object, but I am gettin nullpointerException.
Here is my model class:
public class Cheque {
private String payeeName;
private String accountNumber;
private String ifsCode;
private String micr;
private String bankName;
public Cheque() {
super();
// TODO Auto-generated constructor stub
}
public Cheque(String payeeName, String accountNumber, String ifsCode, String micr, String bankName) {
super();
this.payeeName = payeeName;
this.accountNumber = accountNumber;
this.ifsCode = ifsCode;
this.micr = micr;
this.bankName = bankName;
}
public String getPayeeName() {
return payeeName;
}
public void setPayeeName(String payeeName) {
this.payeeName = payeeName;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getIfsCode() {
return ifsCode;
}
public void setIfscCode(String ifsCode) {
this.ifsCode = ifsCode;
}
public String getMicr() {
return micr;
}
public void setMicr(String micr) {
this.micr = micr;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
Below I am posting the method in which I am invoking a Python program and getting a Json response from it:
public class RunPython {
public static void main(String[] args) throws IOException,ScriptException,NullPointerException{
// TODO Auto-generated method stub
Process p = Runtime.getRuntime().exec("python <path to file>/reg.py");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line ;
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
} finally {
in.close();
}
ObjectMapper mapper = new ObjectMapper();
try {
Cheque cheque = mapper.readValue(line, Cheque.class);
System.out.println("Java object :");
System.out.println(cheque);
}
catch (JsonGenerationException ex) {
ex.printStackTrace();
}
catch (JsonMappingException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}}}
The JSON response which I am getting is:
{
"bankName": [
"Bank"
],
"accountNumber": [
"989898989898"
],
"ifsCode": [
"0000000"
],
"micr": [
"0000000"
],
"payeeName": [
"name"
]
}
After running the program I am getting the JSON response as expected, but while converting it to a Java object it is showing nullPointerException in the main thread. Help me out to find where I am making the mistake.
You consume/exhaust all your Process Inputstream here when printing it :
try {
while((line =in.readLine()) != null) {
System.out.println(line);
}
And later on when you call the below it's already null :
Cheque cheque = mapper.readValue(line, Cheque.class);
You'd have to process it in the above while loop, instead of only printing it out
When you reach the statement:
Cheque cheque = mapper.readValue(line, Cheque.class);
variable line is null.
So you can either rebuild the JSON string (with a StringBuilder), or remove the code that prints the response, and parse the JSON directly from p.getInputStream().
Your Java object has String value, but JSON has array type ([ ])
[Unable to access property of another object stored in Arraylist]
I am creating an function to get JSON input in object from RESTful Web service input and format it again in JSON format to call other web service.
I have limitation that I can not use any JSON API for object mapping hence using Java reflection core API.
I am able to create JSON format from Input for simple elements but unable to access nested elements (another user defined POJO class ). I am using arraylist.
Input
{
"GenesisIncidents": {
"service": "Transmission",
"affectedCI": "22BT_ORNC03",
"opt_additionalAffectedItems": [
{
"itemType": "NODE-ID",
"ItemName": "22BT_ORNC03"
},
{
"ItemType": "CCT",
"ItemName": "A_circuit_id"
}]
}
}
GenesisIncidents.class
import java.util.ArrayList;
import java.util.Date;
public class GenesisIncidents {
private String service;
private String affectedCI;
private ArrayList<AdditionalAffectedItems> opt_additionalAffectedItems;
public GenesisIncidents(){}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getAffectedCI() {
return affectedCI;
}
public void setAffectedCI(String affectedCI) {
this.affectedCI = affectedCI;
}
public ArrayList<AdditionalAffectedItems> getOpt_additionalAffectedItems() {
return opt_additionalAffectedItems;
}
public void setOpt_additionalAffectedItems(ArrayList<AdditionalAffectedItems> opt_additionalAffectedItems) {
this.opt_additionalAffectedItems = opt_additionalAffectedItems;
}
}
AdditionalAffectedItems.class
public class AdditionalAffectedItems {
private String itemType;
private String itemName;
public AdditionalAffectedItems(){
super();
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
Implemetation
public void updateTicketExt(GenesisIncidents genesisIncidents) {
try{
Field allFields[]=genesisIncidents.getClass().getDeclaredFields();
Method allMethods[] = genesisIncidents.getClass().getDeclaredMethods();
String jsonString ="{\r\n \""+genesisIncidents.getClass().getName().toString().substring(48)+"\": {";
final String preStr="\r\n \""; //To create a JSON object format.
final String postStr="\": "; //To create a JSON object format.
int totalNoOfFields=allFields.length;
for (Field field : allFields) {
System.out.println(field.getType());
String getter="get"+StringUtils.capitalize(field.getName());
Method method= genesisIncidents.getClass().getMethod(getter, null);
try{
if(field.getType().toString().contains("Integer"))
jsonString=jsonString + preStr + field.getName() + postStr +method.invoke(genesisIncidents).toString()+",";
else
jsonString=jsonString + preStr + field.getName() + postStr +"\""+method.invoke(genesisIncidents).toString()+"\",";
if(field.getType().toString().contains("ArrayList")){
System.out.println("ArrayListElement found");
genesisIncidents.getOpt_additionalAffectedItems().forEach(obj->{System.out.println(obj.getItemName());});
//convertArrayToJSON(field, genesisIncidents);
}
}catch(NullPointerException npe)
{
System.out.println("Null value in field.");
continue;
}
}
jsonString=jsonString.substring(0,jsonString.length()-1);
jsonString=jsonString+"\r\n }\r\n }";
System.out.println("\n"+jsonString);
}catch(Exception jex){
jex.printStackTrace();
}
}
My below code line is unable to access object stored under array list.
genesisIncidents.getOpt_additionalAffectedItems().forEach(obj->{System.out.println(obj.getItemName());});
OUTPUT
karaf#root>class java.lang.String
class java.lang.String
class java.lang.String
class java.util.ArrayList
ArrayListElement found
null
null
{
"GenesisIncidents": {
"service": "Transmission",
"affectedCI": "22BT_ORNC03",
"opt_additionalAffectedItems": " [org.apache.servicemix.examples.camel.rest.model.AdditionalAffectedItems#5881a 895, org.apache.servicemix.examples.camel.rest.model.AdditionalAffectedItems#399b4e eb]"
}
}
I have fiddled around with your example I have managed to get it working. This will produce the correct JSON string by passing in an instance of a GenesisIncident object. I guess that there is much room for improvement here but this can serve as an example.
public static String genesisToJson(GenesisIncidents incidents) {
try{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{\r\n \"")
.append(incidents.getClass().getSimpleName())
.append("\": {");
Field allFields[] = incidents.getClass().getDeclaredFields();
for (Field field : allFields) {
String getter = getGetterMethod(field);
Method method = incidents.getClass().getMethod(getter, null);
try{
if(field.getType().isAssignableFrom(Integer.class)) {
jsonBuilder.append(preStr).append(field.getName()).append(postStr)
.append(method.invoke(incidents).toString()).append(",");
} else if (field.getType().isAssignableFrom(String.class)) {
jsonBuilder.append(preStr).append(field.getName()).append(postStr).append("\"")
.append(method.invoke(incidents).toString()).append("\",");
} else if (field.getType().isAssignableFrom(List.class)) {
System.out.println("ArrayListElement found");
getInnerObjectToJson(field, incidents.getOptItems(), jsonBuilder);
}
} catch(NullPointerException npe) {
System.out.println("Null value in field.");
continue;
}
}
jsonBuilder.append("\r\n } \r\n }");
return jsonBuilder.toString();
}catch(Exception jex){
jex.printStackTrace();
}
return null;
}
private static void getInnerObjectToJson(Field field, List<AdditionalAffectedItems> items, StringBuilder builder)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
builder.append(preStr).append(field.getName()).append(postStr).append("[");
for (var item : items) {
var fields = List.of(item.getClass().getDeclaredFields());
builder.append("{");
for (var f : fields) {
String getter = getGetterMethod(f);
Method method = item.getClass().getMethod(getter, null);
builder.append(preStr).append(f.getName()).append(postStr).append("\"")
.append(method.invoke(item).toString()).append("\"");
if (!(fields.indexOf(f) == (fields.size() - 1))) {
builder.append(",");
}
}
if (items.indexOf(item) == (items.size() - 1)) {
builder.append("}\r\n");
} else {
builder.append("},\r\n");
}
}
builder.append("]");
}
private static String getGetterMethod(Field field) {
return "get" + StringUtils.capitalize(field.getName());
}
I need to map JSON obj to a class and its arrays to ArrayList in Android and it should have all the children data as well. (with nested arraylists too) and i need to convert updated data list again to jsonobject
my json string is
{
"type": "already_planted",
"crops": [
{
"crop_id": 1,
"crop_name": "apple",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "10"
},
{
"planted_by": "A person"
}
]
},
{
"created_id": "2017-01-30",
"questions": [
{
"plants": "15"
},
{
"planted_by": "B person"
}
]
}
]
},
{
"crop_id": 2,
"crop_name": "Cashew",
"crop_details": [
{
"created_id": "2017-01-17",
"questions": [
{
"plants": "11"
},
{
"planted_by": "c person"
}
]
}
]
}
]
}
First of all, you need to create the class that you are going to map JSON inside.
Fortunately, there is a website that can do it for you here
secondly, you can use google Gson library for easy mapping
1. add the dependency.
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2. from your object to JSON.
MyData data =new MyData() ; //initialize the constructor
Gson gson = new Gson();
String Json = gson.toJson(data ); //see firstly above above
//now you have the json string do whatever.
3. from JSON to object .
String jsonString =doSthToGetJson(); //http request
MyData data =new MyData() ;
Gson gson = new Gson();
data= gson.fromJson(jsonString,MyData.class);
//now you have Pojo do whatever
for more information about gson see this tutorial.
If you use JsonObject, you can define your entity class as this:
public class Entity {
String type;
List<Crops> crops;
}
public class Crops {
long crop_id;
String crop_name;
List<CropDetail> crop_details;
}
public class CropDetail {
String created_id;
List<Question> questions;
}
public class Question {
int plants;
String planted_by;
}
public void convert(String json){
JsonObject jsonObject = new JsonObject(jsonstring);
Entity entity = new Entity();
entity.type = jsonObject.optString("type");
entity.crops = new ArrayList<>();
JsonArray arr = jsonObject.optJSONArray("crops");
for (int i = 0; i < arr.length(); i++) {
JSONObject crops = arr.optJSONObject(i);
Crops cps = new Crops();
cps.crop_id = crops.optLong("crop_id");
cps.crop_name = crops.optString("crop_name");
cps.crop_details = new ArrayList<>();
JsonArray details = crops.optJsonArray("crop_details");
// some other serialize codes
..........
}
}
So you can nested to convert your json string to an entity class.
Here is how I do it without any packages, this do the work for me for small use cases:
My modal class:
package prog.com.quizapp.models;
import org.json.JSONException;
import org.json.JSONObject;
public class Question {
private String question;
private String correct_answer;
private String answer_a;
private String answer_b;
private String answer_c;
private String answer_d;
public Question() {
}
public Question(String question, String answer_a, String answer_b, String answer_c, String answer_d, String correct_answer) {
this.question = question;
this.answer_a = answer_a;
this.answer_b = answer_b;
this.answer_c = answer_c;
this.answer_d = answer_d;
this.correct_answer = correct_answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getCorrect_answer() {
return correct_answer;
}
public void setCorrect_answer(String correct_answer) {
this.correct_answer = correct_answer;
}
public String getAnswer_a() {
return answer_a;
}
public void setAnswer_a(String answer_a) {
this.answer_a = answer_a;
}
public String getAnswer_b() {
return answer_b;
}
public void setAnswer_b(String answer_b) {
this.answer_b = answer_b;
}
public String getAnswer_c() {
return answer_c;
}
public void setAnswer_c(String answer_c) {
this.answer_c = answer_c;
}
public String getAnswer_d() {
return answer_d;
}
public void setAnswer_d(String answer_d) {
this.answer_d = answer_d;
}
#Override
public String toString() {
return "Question{" +
"question='" + question + '\'' +
", correct_answer='" + correct_answer + '\'' +
", answer_a='" + answer_a + '\'' +
", answer_b='" + answer_b + '\'' +
", answer_c='" + answer_c + '\'' +
", answer_d='" + answer_d + '\'' +
'}';
}
public static Question fromJson(JSONObject obj) throws JSONException {
return new Question(
obj.getString("question"),
obj.getString("answer_a"),
obj.getString("answer_b"),
obj.getString("answer_c"),
obj.getString("answer_d"),
obj.getString("correct_answer"));
}
}
And I have another class to get the json file from assets directory and mapped JsonObject to my model class Question:
package prog.com.quizapp.utils;
import android.content.Context;
import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import prog.com.quizapp.models.Question;
public class JsonSqlQueryMapper {
private Context mContext;
public JsonSqlQueryMapper(Context context) {
this.mContext = context;
}
private static final String TAG = "JsonSqlQueryMapper";
public JSONObject loadJSONFromAsset() {
String json = null;
try {
InputStream is = mContext.getAssets().open("quiz_app.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject quizObject = new JSONObject(json).getJSONObject("quiz");
return quizObject;
} catch (Exception e) {
Log.d(TAG, "loadJSONFromAsset: " + e.getMessage());
return null;
}
}
public ArrayList<Question> generateInsertQueryForJsonObjects() {
ArrayList<Question> questions = new ArrayList<>();
JSONObject jsonObject = loadJSONFromAsset();
try {
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject value = jsonObject.getJSONObject(key);
Question question = Question.fromJson(value.getJSONObject("question_two"));
questions.add(question);
Log.d(TAG, "generateInsertQueryForJsonObjects: " + question.getAnswer_a());
}
} catch (Exception e) {
e.printStackTrace();
}
return questions;
}
}
And in my MainActivity -> onCreate:
JsonSqlQueryMapper mapper = new JsonSqlQueryMapper(MainActivity.this);
mapper.generateInsertQueryForJsonObjects();
To check that everything working as I want. Here is the json file if you want to check https://github.com/Blasanka/android_quiz_app/blob/sqlite_db_app/app/src/main/assets/quiz_app.json
Regards!
I have not seen an (answered) example on the web which discusses this kind of nested-json-array.
JSON to be parsed:
{
"Field": {
"ObjectsList": [
{
"type": "Num",
"priority": "Low",
"size": 3.43
},
{
"type": "Str",
"priority": "Med",
"size": 2.61
}
]
}
}
I created a class for each 'level' of nested json block. I want to be able to parse the contents of the "ObjectList" array.
Can anyone help me to parse this JSON using Gson in Java?
Any hints or code-snippets would be greatly appreciated.
My approach is the following:
public static void main (String... args) throws Exception
{
URL jsonUrl = new URL("http://jsonUrl.com") // cannot share the url
try (InputStream input = jsonUrl.openStream();
BufferedReader buffReader = new BufferedReader (new InputStreamReader (input, "UTF-8")))
{
Gson gson = new GsonBuilder().create();
ClassA classA = gson.fromJson(buffReader, ClassA.class);
System.out.println(classA);
}
}
}
class ClassA
{
private String field;
// getter & setter //
}
class ClassB
{
private List<ClassC> objList;
// getter & setter //
}
clas ClassC
{
private String type;
private String priority;
private double size;
// getters & setters //
public String printStr()
{
return String.format(type, priority, size);
}
}
The following snippet and source file would help you:
https://github.com/matpalm/common-crawl-quick-hacks/blob/master/links_in_metadata/src/com/matpalm/MetaDataToTldLinks.java#L17
private static ParseResult NO_LINKS = new ParseResult(new HashSet<String>(), 0);
private JsonParser parser;
public static void main(String[] s) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(s[0]));
MetaDataToTldLinks metaDataToTldLinks = new MetaDataToTldLinks();
while (reader.ready()) {
String[] fields = reader.readLine().split("\t");
ParseResult outboundLinks = metaDataToTldLinks.outboundLinks(fields[1]);
System.out.println(tldOf(fields[0]) + " " + outboundLinks.links);
}
}
public MetaDataToTldLinks() {
this.parser = new JsonParser();
}
public ParseResult outboundLinks(String jsonMetaData) {
JsonObject metaData = parser.parse(jsonMetaData.toString()).getAsJsonObject();
if (!"SUCCESS".equals(metaData.get("disposition").getAsString()))
return NO_LINKS;
JsonElement content = metaData.get("content");
if (content == null)
return NO_LINKS;
JsonArray links = content.getAsJsonObject().getAsJsonArray("links");
if (links == null)
return NO_LINKS;
Set<String> outboundLinks = new HashSet<String>();
int numNull = 0;
for (JsonElement linke : links) {
JsonObject link = linke.getAsJsonObject();
if ("a".equals(link.get("type").getAsString())) { // anchor
String tld = tldOf(link.get("href").getAsString());
if (tld == null)
++numNull;
else
outboundLinks.add(tld);
}
}
return new ParseResult(outboundLinks, numNull);
}
public static String tldOf(String url) {
try {
String tld = new URI(url).getHost();
if (tld==null)
return null;
if (tld.startsWith("www."))
tld = tld.substring(4);
tld = tld.trim();
return tld.length()==0 ? null : tld;
}
catch (URISyntaxException e) {
return null;
}
}
public static class ParseResult {
public final Set<String> links;
public final int numNull;
public ParseResult(Set<String> links, int numNull) {
this.links = links;
this.numNull = numNull;
}
}
How about this snippet?:
if (json.isJsonArray()) {
JsonArray array = json.getAsJsonArray();
List<Object> out = Lists.newArrayListWithCapacity(array.size());
for (JsonElement item : array) {
out.add(toRawTypes(item));
}
}
Is there any module in Java equivalent to python's shelve module? I need this to achieve dictionary like taxonomic data access. Dictionary-like taxonomic data access is a powerful way to save Python objects in a persistently easy access database format. I need something for the same purpose but in Java.
I also needed this, so I wrote one. A bit late, but maybe it'll help.
It doesn't implement the close() method, but just use sync() since it only hold the file open when actually writing it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class Shelf extends HashMap<String, Object> {
private static final long serialVersionUID = 7127639025670585367L;
private final File file;
public static Shelf open(File file) {
Shelf shelf = null;
try {
if (file.exists()) {
final FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
shelf = (Shelf) ois.readObject();
ois.close();
fis.close();
} else {
shelf = new Shelf(file);
shelf.sync();
}
} catch (Exception e) {
// TODO: handle errors
}
return shelf;
}
// Shelf objects can only be created or opened by the Shelf.open method
private Shelf(File file) {
this.file = file;
sync();
}
public void sync() {
try {
final FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);
oos.close();
fos.close();
} catch (Exception e) {
// TODO: handle errors
}
}
// Simple Test Case
public static void main(String[] args) {
Shelf shelf = Shelf.open(new File("test.obj"));
if (shelf.containsKey("test")) {
System.out.println(shelf.get("test"));
} else {
System.out.println("Creating test string. Run the program again.");
shelf.put("test", "Hello Shelf!");
shelf.sync();
}
}
}
You could use a serialisation library like Jackson which serialises POJOs to JSON.
An example from the tutorial:
Jackson's org.codehaus.jackson.map.ObjectMapper "just works" for
mapping JSON data into plain old Java objects ("POJOs"). For example,
given JSON data
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
It takes two lines of Java to turn it into a User instance:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
Where the User class looks something like this (from an entry on Tatu's blog):
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}