libs-for-android:JsonContentHandler的示例?

时间:2011-01-10 12:33:17

标签: android json parsing libs

我正在使用libs-for-android的feed.jar,我需要解析json数据。 我已经创建了类似于演示中使用的XmlContentHandler.java的JsonContentHandler.java类。

您能举例说明如何使用JsonContentHandler吗?

谢谢。

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

1 个答案:

答案 0 :(得分:1)

示例输入:

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

示例代码:

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());
    }
}