0

I have a PHP JSON that sends me JSONArray.

  public JSONArray lastTweet()throws ClientProtocolException,IOException,JSONException{
      StringBuilder url = new StringBuilder(URL);
      HttpGet get = new HttpGet(url.toString());
      HttpResponse r = client.execute(get);
      int status = r.getStatusLine().getStatusCode();
      if(status == 200){
          HttpEntity e = r.getEntity();
          String data = EntityUtils.toString(e);
          JSONArray timeline = new JSONArray(data);
         return timeline;
      }
    return null;

  }

I can get Object and values from this JSONArray (timeline), but it work only then application have internet conection. I want to save this JSON in my internal storage like a json file and after work with this file in offline mod. How i can do this?

4

1 回答 1

0

尝试使用JSON Simple库,它可以轻松编码/解码 JSON 文件。

示例:编码

然后就很简单了:

try {
    outStream = openFileOutput("tweet.json", Context.MODE_PRIVATE);
    outStream.write(json.getJSONString().getBytes());
    outStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

但是,如果您不想永远存储它,或者出于重新发送的目的,我建议使用Cache Mind 缓存可以自动擦除,所以这取决于您。与往常一样,更多关于这方面的信息,请访问 Android 开发者网站:Android: Saving Files # Write Internal Storage

更新: 原来android JSONObject.toString() 产生连贯的JSON输出,可以按照上面描述的方式保存到文件中,没有任何第三方库,但是您需要自己将其编组回JSONObject/Array/Primitive,这将需要一些额外的工作。

于 2014-08-26T15:31:50.170 回答