Changing library from org.json to Jackson for parsing JSON

I've been using the stock org.json library and am familiar with this. I now want to use the Jackson library for performance reasons, but am struggling with adapting to what looks like a very different framework. Take the following JSON :

{"result":[[{"usUserName":"FRED","usActive":true},{"usUserName":"JIM","usActive":true},{"usUserName":"DAVID","usActive":true}]]}

With org.json I am parsing this as follows :

try {
    JSONArray jsonRecordset = response.getJSONArray("result").getJSONArray(0);
    JSONObject jsonFirstRecord = jsonRecordset.getJSONObject(0);
    Log.i("myloginfo", jsonFirstRecord.getString("usUserName"));
} catch (JSONException e) {
    e.printStackTrace();
}

I'd like to replicate this with Jackson but can't see where to go, as it looks very different. My JSON is coming from a web service which I don't have control over. The data above is just for illustration, my actual data is much larger hence me wanting the best performance.

Answers


The usual way is that instead of manually slicing and dicing things, you define a Java class (or multiple classes) that has structure compatible with JSON. Like so:

public class Response {
  public UserInfo[][] result;
}
public class UserInfo {
  public String usUserName;
  public boolean usActive;
}

ObjectMapper mapper = new ObjectMapper(); // must reuse for good performance
Response resp = mapper.readValue(jsonInput, Response.class);
// and use 'resp' however you want, now has the expected data.

It is also possibly to use Jackson same way as json.org, with so-called Tree Model; for that you can check out tutorials. It works better when data does not have good object structure (i.e. wasn't designed to be easily accessible from OO languages), or if you only need a small snippet from within large documents.


Need Your Help

formatting string output with linebreaks and tabs in Python?

python django string formatting fixture

Im trying to extract some data from a large batch of files and convert them to a specific (JSON) format for importing into a database using Django Fixtures

Android Client - Java Server: how many clients can a server support at the same time?

java android mysql jdbc client-server

I did not find any adequate answers to my question on Internet. So, I am asking here.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.