【问题标题】:BlackBerry read json string from an URL黑莓从 URL 读取 json 字符串
【发布时间】:2013-05-22 01:10:54
【问题描述】:

我试图读取一个 json 字符串 loading from an URL,但我找不到完整的代码示例。任何人都可以提供或指向我完整的客户端代码。我是 BB 开发的新手。

this 是我所做的,但仍然无法正常工作,请帮助我。

谢谢!

【问题讨论】:

  • Blackberry json parser的可能重复
  • 我也问过这个问题,但它仍然不起作用。我想我必须启动新线程才能访问网络,但我仍然不知道。请帮忙。谢谢!
  • 我对该问题的回答将解决您的问题。你试过吗?
  • 是否需要启动新线程才能在 BB 中发出 http 请求??
  • @Grant,我认为您正在同时处理几个问题。您需要将问题分解为子问题并独立解决每个问题。对于这个问题,首先你需要知道如何建立一个 HTTP 连接并从 URL 中读取数据。完成该任务后,您需要开始 JSON 解析,它将使用字符串作为输入。最后,您需要解决其他 UI 相关问题(pushModalScreen 错误、Dialog 错误等)。

标签: blackberry blackberry-simulator blackberry-jde blackberry-eclipse-plugin


【解决方案1】:

要从 URL 读取和解析数据,您需要实现两个例程。其中第一个将处理通过 HTTP 连接从指定 URL 读取数据,第二个将解析数据。

查看下面的应用HttpUrlReaderDemoApp,它会先从指定的URL读取数据,然后解析获取到的数据。

类:

  • HttpUrlReaderDemoApp - UiApplication 实例
  • HttpResponseListener - 用于通知其他类有关 HTTP 请求状态的接口
  • HttpUrlReader - 从给定的 url 读取数据
  • AppMainScreen - MainScreen 实例
  • DataParser - 解析数据
  • DataModel - 数据定义

截图:

  • 数据请求

  • 数据检索成功时

  • 解析数据

实施:

HttpUrlReaderDemoApp

public class HttpUrlReaderDemoApp extends UiApplication {
    public static void main(String[] args) {
        HttpUrlReaderDemoApp theApp = new HttpUrlReaderDemoApp();
        theApp.enterEventDispatcher();
    }

    public HttpUrlReaderDemoApp() {
        pushScreen(new AppMainScreen("HTTP Url Reader Demo Application"));
    }
}

HttpResponseListener

public interface HttpResponseListener {
    public void onHttpResponseFail(String message, String url);

    public void onHttpResponseSuccess(byte bytes[], String url);
}

HttpUrlReader

public class HttpUrlReader implements Runnable {
    private String url;
    private HttpResponseListener listener;

    public HttpUrlReader(String url, HttpResponseListener listener) {
        this.url = url;
        this.listener = listener;
    }

    private String getConncetionDependentUrlSuffix() {
        // Not implemented
        return "";
    }

    private void notifySuccess(byte bytes[], String url) {
        if (listener != null) {
            listener.onHttpResponseSuccess(bytes, url);
        }
    }

    private void notifyFailure(String message, String url) {
        if (listener != null) {
            listener.onHttpResponseFail(message, url);
        }
    }

    private boolean isValidUrl(String url) {
        return (url != null && url.length() > 0);
    }

    public void run() {
        if (!isValidUrl(url) || listener == null) {
            String message = "Invalid parameters.";
            message += !isValidUrl(url) ? " Invalid url." : "";
            message += (listener == null) ? " Invalid HttpResponseListerner instance."
                    : "";
            notifyFailure(message, url);
            return;
        }

        // update URL depending on connection type
        url += DeviceInfo.isSimulator() ? ";deviceside=true"
                : getConncetionDependentUrlSuffix();

        // Open the connection and retrieve the data
        try {
            HttpConnection httpConn = (HttpConnection) Connector.open(url);
            int status = httpConn.getResponseCode();
            if (status == HttpConnection.HTTP_OK) {
                InputStream input = httpConn.openInputStream();
                byte[] bytes = IOUtilities.streamToBytes(input);
                input.close();
                notifySuccess(bytes, url);
            } else {
                notifyFailure("Failed to retrieve data, HTTP response code: "
                        + status, url);
                return;
            }
            httpConn.close();
        } catch (Exception e) {
            notifyFailure("Failed to retrieve data, Exception: ", e.toString());
            return;
        }
    }
}

AppMainScreen

public class AppMainScreen extends MainScreen implements HttpResponseListener {
    private final String URL = "http://codeincloud.tk/json_android_example.php";

    public AppMainScreen(String title) {
        setTitle(title);
    }

    private MenuItem miReadData = new MenuItem("Read data", 0, 0) {
        public void run() {
            requestData();
        }
    };

    protected void makeMenu(Menu menu, int instance) {
        menu.add(miReadData);
        super.makeMenu(menu, instance);
    }

    public void close() {
        super.close();
    }

    public void showDialog(final String message) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
                Dialog.alert(message);
            }
        });
    }

    private void requestData() {
        Thread urlReader = new Thread(new HttpUrlReader(URL, this));
        urlReader.start();
        showDialog("Request for data from\n \"" + URL + "\"\n started.");
    }

    public void onHttpResponseFail(String message, String url) {
        showDialog("Failure Mesage:\n" + message + "\n\nUrl:\n" + url);
    }

    public void onHttpResponseSuccess(byte bytes[], String url) {
        showDialog("Data retrived from:\n" + url + "\n\nData:\n"
                + new String(bytes));

        // now parse response
        DataModel dataModel = DataParser.getData(bytes);
        if (dataModel == null) {
            showDialog("Failed to parse data: " + new String(bytes));
        } else {
            showDialog("Parsed Data:\nName: " + dataModel.getName()
                    + "\nVersion: " + dataModel.getVersion());
        }
    }
}

数据解析器

public class DataParser {
    private static final String NAME = "name";
    private static final String VERSION = "version";

    public static DataModel getData(byte data[]) {
        String rawData = new String(data);
        DataModel dataModel = new DataModel();

        try {
            JSONObject jsonObj = new JSONObject(rawData);
            if (jsonObj.has(NAME)) {
                dataModel.setName(jsonObj.getString(NAME));
            }
            if (jsonObj.has(VERSION)) {
                dataModel.setVersion(jsonObj.getString(VERSION));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return dataModel;
    }
}

数据模型

public class DataModel {
    private String name;
    private String version;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String model) {
        this.version = model;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-19
    • 2013-02-21
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    相关资源
    最近更新 更多