加载在线存储的JSON文件

时间:2015-03-24 00:10:12

标签: android json

是否有一种简单的方法可以将下面的代码指向具有JSON数据的URL。之前我在Assets文件夹中使用了我的Json文件:

InputStream is = context.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();

该data.json文件现在存储在网上。如果我得到该URL的字符串为String URL =" http ... whatever .... data.json"如何在第一行代码中初始化InputStream?

2 个答案:

答案 0 :(得分:0)

该代码特定于从文件中读取。您需要设置AsyncTask并在后台线程中提取数据。

此页面解释了这些问题并提供了很好的示例。

http://developer.android.com/training/basics/network-ops/connecting.html

更新1:

以下是来自项目的代码,该项目提取数据并对其进行解析并填充java对象:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;

public class RestServices
{

   public static String getServerAddress()
   {
      return "http://192.168.96.179:8090/";
   }

   public static String getRestURI()
   {
      return "api/";
   }

   public static <T> T getExternalData(Class<T> clazz, String uri) throws IOException
   {
      String responseString = "";
      try
      {
         HttpClient httpclient = new DefaultHttpClient();
         String address = getServerAddress() +  getRestURI() + uri;
         HttpResponse response = httpclient.execute(new HttpGet(address));
         StatusLine statusLine = response.getStatusLine();
         if(statusLine.getStatusCode() == HttpStatus.SC_OK){
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             response.getEntity().writeTo(out);
             out.close();
             responseString = out.toString();
         } else{
             response.getEntity().getContent().close();
             throw new IOException(statusLine.getReasonPhrase());
         }
      }
      catch (ClientProtocolException e)
      {

      }

      Gson gson = new Gson();
      T object = gson.fromJson(responseString, clazz);
      return object;
   }


}

我怎么称呼它:

class SiteConfigTask extends AsyncTask<Void, SiteConfig, SiteConfig>
   {

      @Override
      protected SiteConfig doInBackground(Void... none) 
      {
         SiteConfig sc = null;
         try
         {
            sc = RestServices.getExternalData(SiteConfig.class, "siteconfig");
         } catch (IOException e)
         {
            Log.e(TAG,"Failed to fetch siteconfig", e);
         }
          return sc;
      }

      @Override
      protected void onPostExecute(SiteConfig result) 
      {
         super.onPostExecute(result);

         if ( result == null )
         {
            EventBus.getDefault().post(new ConfigurationFetchErrorEvent());
         }
         else
         {
            // Adds an additional empty stream if there are
            // and odd number of streams, the new stream will be disabled.
            if ( result.getStreamList().size() % 2 != 0)
            {
               Stream s = new Stream();
               s.setEnabled(false);
               result.getStreamList().add(s);
            }

            updateSiteConfig(result);
         }
      }
  }

答案 1 :(得分:0)

您可以通过HttpURLConnection请求资源,例如下面的代码段。

    HttpURLConnection connection = null;
    InputStream inputStream = null;
    try {
        URL url = new URL("http://www.example.com/data.json");

        connection = (HttpURLConnection) url.openConnection();
        inputStream = connection.getInputStream();

        int size = inputStream.available();
        byte[] buffer = new byte[size];
        inputStream.read(buffer);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }