在线阅读JSON android

时间:2013-05-16 09:51:29

标签: android json

我有在线JSON文件,如下所示:

{  
    "iPadVersion": "1.0",
    "AndroidVersion": "1.0"
}

我试图像这样读取它(这部分代码在AsyncTask中):

JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http://mylink/db.json");
String str = "tmp";

            try {
                  str = json.getString("AndroidVersion");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            Log.d(TAG, ""+str);

我在log.d上总是“tmp”,它不起作用。

StactTrace:

    05-16 12:54:08.605: W/System.err(20406): java.io.FileNotFoundException: /http:/mylink/db.json: open failed: ENOENT (No such file or directory)
    05-16 12:54:08.605: W/System.err(20406):    at libcore.io.IoBridge.open(IoBridge.java:406)
    05-16 12:54:08.605: W/System.err(20406):    at java.io.FileInputStream.<init>(FileInputStream.java:78)
    05-16 12:54:08.605: W/System.err(20406):    at java.io.FileInputStream.<init>(FileInputStream.java:105)
    05-16 12:54:08.605: W/System.err(20406):    at java.io.FileReader.<init>(FileReader.java:66)
    05-16 12:54:08.605: W/System.err(20406):    at com.weterworks.JSONParser.getJSONFromUrl(JSONParser.java:37)
    05-16 12:54:08.605: W/System.err(20406):    at com.weterworks.MainActivity$sync.<init>(MainActivity.java:359)
    05-16 12:54:08.605: W/System.err(20406):    at com.weterworks.MainActivity.onCreate(MainActivity.java:263)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.Activity.performCreate(Activity.java:4465)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    05-16 12:54:08.605: W/System.err(20406):    at android.os.Handler.dispatchMessage(Handler.java:99)
    05-16 12:54:08.605: W/System.err(20406):    at android.os.Looper.loop(Looper.java:137)
    05-16 12:54:08.605: W/System.err(20406):    at android.app.ActivityThread.main(ActivityThread.java:4424)
    05-16 12:54:08.605: W/System.err(20406):    at java.lang.reflect.Method.invokeNative(Native Method)
    05-16 12:54:08.615: W/System.err(20406):    at java.lang.reflect.Method.invoke(Method.java:511)
    05-16 12:54:08.615: W/System.err(20406):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    05-16 12:54:08.615: W/System.err(20406):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    05-16 12:54:08.615: W/System.err(20406):    at dalvik.system.NativeStart.main(Native Method)
    05-16 12:54:08.615: W/System.err(20406): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
    05-16 12:54:08.615: W/System.err(20406):    at libcore.io.Posix.open(Native Method)
    05-16 12:54:08.615: W/System.err(20406):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
    05-16 12:54:08.615: W/System.err(20406):    at libcore.io.IoBridge.open(IoBridge.java:390)
    05-16 12:54:08.615: W/System.err(20406):    ... 20 more
    05-16 12:54:08.615: W/System.err(20406): org.json.JSONException: No value for AndroidVersion
    05-16 12:54:08.615: W/System.err(20406):    at org.json.JSONObject.get(JSONObject.java:354)
    05-16 12:54:08.615: W/System.err(20406):    at org.json.JSONObject.getString(JSONObject.java:510)
    05-16 12:54:08.615: W/System.err(20406):    at com.weterworks.MainActivity$sync.doInBackground(MainActivity.java:404)
    05-16 12:54:08.615: W/System.err(20406):    at com.weterworks.MainActivity$sync.doInBackground(MainActivity.java:1)
    05-16 12:54:08.615: W/System.err(20406):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
    05-16 12:54:08.615: W/System.err(20406):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    05-16 12:54:08.625: W/System.err(20406):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    05-16 12:54:08.625: W/System.err(20406):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
    05-16 12:54:08.625: W/System.err(20406):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    05-16 12:54:08.625: W/System.err(20406):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    05-16 12:54:08.625: W/System.err(20406):    at java.lang.Thread.run(Thread.java:856)

JsonParser类:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {


    try {
        BufferedReader reader = new BufferedReader(new FileReader(url));
        String line, results = "";
        while ((line = reader.readLine()) != null) {
            results += line;
        }
        reader.close();

        jObj = new JSONObject(results);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jObj;

}

}

2 个答案:

答案 0 :(得分:2)

您正在尝试从网址中读取数据,但您在流链中使用了FileReader。这根本不起作用,因为FileReader将其字符串参数解释为本地系统上的文件(请参阅Javadoc)。

您需要做的是使用HTTP库从给定的URL下载数据,然后将其解析为JSON对象。我在下面展示了一个示例,使用SDK中的内置HTTP类:

public class JSONParser {
    private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31";

    public JSONObject getJSONFromUrl(String url) {

        try {
            final HttpURLConnection connection = (HttpURLConnection) new URL(
                    url).openConnection();
            connection.setRequestProperty("User-Agent", USER_AGENT);

            if (connection.getResponseCode() == 200) {
                final BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));

                String line = null;
                final StringBuffer buffer = new StringBuffer(4096);
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                reader.close();

                final JSONObject jObj = new JSONObject(buffer.toString());
                return jObj;
            } else {
                return null;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

旁注:不要为此创建自己的解析实用程序,而是可以在项目中包含Jackson,并使用此单行程序:

final JsonNode jsonObj = new ObjectMapper().readTree(new URL(
        "http://www.example.com/json"));

答案 1 :(得分:0)

检查您的服务器链接并正确使用它。我想,你有服务器URL的问题。 记录你的url字符串并尝试通过浏览器获取它。