0

这是我在 Stackoverflow 上的第一篇文章,我正在尝试学习 Android。我需要从 android 应用程序中读取一个 json 文件。

我在手机上运行了以下代码,它没有在手机上显示任何内容,我只是得到一个空白屏幕。

我知道有一些方法可以使用 Java 库来解析 json,但这不是我想要的。我想仅使用 Android 提供的工具来完成读取此 json 的操作。这是我的json

我正在使用 Android 4.0.3 这是我的 json 文件数据:

{
    "offers": [
        {
                "id": "1",
                "type":"xyz",
                "description":"blah blah",
                "url":"http://www.example.com/"
        },
        {
                "id": "1",
                "type":"xyz",
                "description":"some description",
                "url":"http://www.example.com/"
        },
        {
                "id": "1",
                "type":"xyz",
                "description":"some description",
                "url":"http://www.example.com/"
        }
    ]
}

这是我的 MainActivity.java

package com.pega.parsejson;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView jsonWrapper;
    HttpClient httpClient;
    JSONObject json;


    final static String offersUrl="http://somewebsite.com/offers.json";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        jsonWrapper=(TextView) findViewById(R.id.jsonWrap);
        httpClient=new DefaultHttpClient();
        new Read().execute("description");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public JSONObject jsonOffers() throws ClientProtocolException, IOException, JSONException {
        //StringBuilder url=new StringBuilder(offersUrl);

        HttpGet get=new HttpGet(offersUrl);
        HttpResponse res=httpClient.execute(get);
        int status=res.getStatusLine().getStatusCode();

        if(status==200){
            HttpEntity e=res.getEntity();
            String data=EntityUtils.toString(e);
            JSONArray timeline=new JSONArray("offers");
            JSONObject jsonOffer=timeline.getJSONObject(0); //returns most recent offer
            return jsonOffer;
        }else{
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
            return null;
        }

    }

    public class Read extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {
            try {
                json=jsonOffers();
                return (String) json.get("description"); //returns string w/ parameter passed in as "description"
            } catch (ClientProtocolException 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 null;
        }

        @Override
        protected void onPostExecute(String result) {
            jsonWrapper.setText(result);
        }

    }

}

我也在使用互联网权限:

这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pega.parsejson"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pega.parsejson.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

下面是我的文本视图:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/jsonWrap"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:text="" />

</RelativeLayout>

这是我的日志:

[2013-08-07 23:35:41 - parseJson] ------------------------------
[2013-08-07 23:35:41 - parseJson] Android Launch!
[2013-08-07 23:35:41 - parseJson] adb is running normally.
[2013-08-07 23:35:41 - parseJson] Performing com.pega.parsejson.MainActivity activity launch
[2013-08-07 23:35:42 - parseJson] Uploading parseJson.apk onto device 'HT25EHX00690'
[2013-08-07 23:35:42 - parseJson] Installing parseJson.apk...
[2013-08-07 23:35:45 - parseJson] Success!
[2013-08-07 23:35:45 - parseJson] Starting activity com.pega.parsejson.MainActivity on device HT25EHX00690
[2013-08-07 23:35:46 - parseJson] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.pega.parsejson/.MainActivity }

请注意,我不想使用任何 json 库来解析我的 json,我只想使用 android 来解析 json。我只是不明白为什么我的 mainActivity.java 没有在手机上显示任何内容。

为我的帖子的长度道歉,对于一个时间敏感的项目真的需要帮助,是的,我已经阅读了 Stackoverflow 上的其他类似问题,但似乎没有人回答这个问题。

有人可以帮我吗?

谢谢

4

3 回答 3

1

尝试这样的事情:

if(status==200){
            HttpEntity e=res.getEntity();
            String data=EntityUtils.toString(e);

            JSONObject jObj;
            JSONArray data = null;
            JSONObject jsonOffer;

            jObj = new JSONObject(data);
            data = jObj.getJSONArray("offers");
            jsonOffer=data.getJSONObject(0);
            return jsonOffer;
    }

获取类似的值

String id = jsonOffer.getString("id");

我们为您的 json 创建了 json 对象。然后我们得到了“Offers”键下的数组。所以我们将数据作为一个数组。然后我们在 jsonoffer 对象中得到了数组的第一个对象。所以我们在 jsonoffer 中有数据,我们可以通过 getString(keyName) 检索值。

希望能帮助到你!!

于 2013-08-08T04:35:10.087 回答
0

我相信你的错误在于代码:

HttpEntity e=res.getEntity();
String data=EntityUtils.toString(e);
JSONArray timeline=new JSONArray("offers");
JSONObject jsonOffer=timeline.getJSONObject(0); //returns most recent offer
return jsonOffer;

原因是您正在创建一个新的 JSONArray,而不是使用您收到的 JSON 中的数组。

相反,您应该使用内置的 JSONObject 解析收到的 JSON,然后选择数组。假设data持有 JSON 文本,您可以执行以下操作:

JSONObject json = new JSONObject(data);
JSONArray timeline = json.getJSONArray("offers");
return timeline.getJSONObject(0); // return most recent offer
于 2013-08-15T07:02:12.910 回答
0

执行以下操作,

public class Read extends AsyncTask<String, Integer, JSONObject>{

        @Override
        protected JSONObjectdoInBackground(String... params) {
            try {
                json=jsonOffers();
                return  json;
            } catch (ClientProtocolException 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 null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {

 try {
            JSONArray offers=result.getJSONArray("offers");
            for(int i=0;i<offers.length();i++)
            {
                JSONObject obj1=offers.getJSONObject(0);
                String desc1=obj1.getString("description");

                JSONObject obj2=offers.getJSONObject(1);
                String desc2=obj2.getString("description");

                JSONObject obj3=offers.getJSONObject(2);
                String desc3=obj3.getString("description");
            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        }

    }

}

现在String desc1,desc2,desc3 分别包含您的 3 个描述。用它做任何你想做的事string

于 2013-08-08T06:01:06.993 回答