0

i'm using feed.jar of libs-for-android, and i need to parse json data. I've founded JsonContentHandler.java class similar to XmlContentHandler.java used in demos.

Can you give me an example on how to use JsonContentHandler?

thank you.

ps: https://code.google.com/p/libs-for-android/

Premier
  • 4,160
  • 6
  • 44
  • 58

1 Answers1

1

Example input:

{"results": [{"id": "1f3d", "title": "Result title", "content": "Some content"}, ...]}

Example code:

public class MyContentHandler extends JsonContentHandler {

    private final MatrixCursor mOutput;

    public MyContentHandler(MatrixCursor cursor) {
        mOutput = cursor;
    }

    @Override
    protected Object getContent(String source) throws JSONException {
        JSONObject data = new JSONObject(source);
        int columnCount = output.getColumnCount();
        JSONArray results = data.getJSONArray("results");
        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            String id = result.getString("id");
            String title = result.getString("title");
            String content = result.getString("content");

            // Generate a positive integer ID for compatibility with CursorAdapter
            Long baseId = Long.valueOf(Math.abs(id.hashCode()));

            RowBuilder builder = output.newRow();
            for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                String columnName = output.getColumnName(columnIndex);
                if (columnName.equals(MyContract.Items._ID)) {
                    builder.add(baseId);
                } else if (columnName.equals(MyContract.Items.ID)) {
                    builder.add(id);
                } else if (columnName.equals(MyContract.Items.TITLE)) {
                    builder.add(title);
                } else if (columnName.equals(MyContract.Items.CONTENT)) {
                    builder.add(content);
                } else {
                    throw new RuntimeException("Unknown column: " + columnName);
                }
            }
        }

        // Tell FeedLoader how many rows were added
        return FeedLoader.documentInfo(results.length());
    }
}