将数据从本地JSON文件解析为java android

时间:2015-03-01 10:29:54

标签: java android json

在网上跟踪了一些例子后,我感到很困惑,所以希望有人可以向我解释下一步我做了什么,并指出我正确的方向。

在我的应用中,我已经创建了一个加载我的JSON文件的功能,该文件位于我的资源文件夹中。

public String loadJSONFromAsset() {
    String json = null;
    try {

        InputStream is = getAssets().open("animals.json");

        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;

}

那么在onCreate中,我有以下一行

JSONObject obj = new JSONObject();

我对如何调用loadJSONFromAsset()感到很困惑,正如我见过的其他示例所做的那样,但这是我理解的方法,直到我到达这里。例如,如何将JSON输出到我创建的TextView中?

由于

编辑 - 抱歉忘记了JSON!

[
{"zooLocation":"Penguin Bay", "animalName":"Humboldt Penguin (Spheniscus humboldti)", "status":"Vulnerable", "naturalHabitat":"Coast of Chile and Peru in South America on islands and rocky areas in burrows", "food":"Small fish", "animalInfo":"Humboldt Penguins grow to 56-70cm long and a weight of up to 4.9kg. The penguins can be distinguished by their spot patterns on their belly", "moreAnimalInfo":"", "interestingFacts":"Penguins can propel themselves at speeds up to 17 mph underwater", "helpfulHints":"", "todaysFeed":"Come and see us at Penguin Bay at 11.30am and 2.30pm - Please check around the park as these times may change"},
{"zooLocation":"Otters and Reindeer", "animalName":"Asian Short-Clawed Otter", "status":"Vulnerable", "naturalHabitat":"Throughout a large area of Asia in wetland systems in freshwater swamps, rivers, mangroves and tidal pools", "food":"A variety of animals living near to the waters edge, including crabs, mussels, frogs and snails", "animalInfo":"Vulnerable in their natural habitat, these are the smallest species of otter in the world and are perfectly at home on land or in water. They live in extended family groups and younger family members help to raise their little brothers and sisters.", "moreAnimalInfo":"", "interestingFacts":"", "helpfulHints":"", "todaysFeed":"Come and see the otter talk and feed at our enclosure at 10.15am - Please check around the park as these times may change"}
]

2 个答案:

答案 0 :(得分:0)

未调用该函数。它只是将整个文件内容写入String但不创建JSONObject。使用您编写的行,您只需创建一个新的空JSONObject

所以你真正想做的是:

public JSONObject loadJSONFromAsset() {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        InputStream is = getAssets().open("animals.json");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        bufferedReader.close();
        return new JSONObject(stringBuilder.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

现在您可以通过标准方法使用JSONObject:

http://developer.android.com/reference/org/json/JSONObject.html

因此,要在onCreate方法中使用JSONObject,您只需执行:

JSONObject obj = loadJSONFromAsset();

答案 1 :(得分:0)

  

如何将JSON输出到我创建的TextView中?

根据给定的JSON,它是一个JSON数组,因为它以[开头,如果响应以{开头,那么它将是一个JSON对象。

所以让我们解析JSON。

try {
            //Main Node
            JSONArray mainNode = new JSONArray(loadJSONFromAsset()); //UPDATED

        //There are 2 objects, so looping through each one
        for(int i=0;i<mainNode.length();i++){

            //Collect JSONObject in ith position
            JSONObject eachObject = mainNode.getJSONObject(i);

            //Assuming there's a TextView and refd. as tvZooLocation...
            tvZooLocation.setText(eachObject.getString("zooLocation"));
            tvAnimalName.setText(eachObject.getString("animalName"));

        }

        //Parsing Finished


    } catch (JSONException e) {
        e.printStackTrace();
    }

<强>已更新

public String loadJSONFromAsset() {
    StringBuilder stringBuilder = new StringBuilder();
    try { 
        InputStream is = getAssets().open("animals.json");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        } 

        bufferedReader.close();
        return stringBuilder.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null; 
}

编辑2: 完成活动

MyChecker.java

package com.shifar.shifz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MyChecker extends Activity {

    TextView tvAnimal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checker);

        tvAnimal = (TextView) findViewById(R.id.tvAnimal);

        try {
            // Main Node
            JSONArray mainNode = new JSONArray(loadJSONFromAsset()); // UPDATED

            // There are 2 objects, so looping through each one
            for (int i = 0; i < mainNode.length(); i++) {

                // Collect JSONObject in ith position
                JSONObject eachObject = mainNode.getJSONObject(i);

                // Assuming there's a TextView and refd. as tvZooLocation...
                tvAnimal.setText(eachObject.getString("zooLocation"));

            }

            // Parsing Finished

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private String loadJSONFromAsset() {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStream is = getAssets().open("animals.json");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(is));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            bufferedReader.close();

            Log.d("X","Response Ready:"+stringBuilder.toString());

            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

布局/ checker.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rlContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:orientation="vertical" >

    <TextView 
        android:id="@+id/tvAnimal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

资产/ animal.json

[
{
    "zooLocation": "Penguin Bay",
    "animalName": "Humboldt Penguin (Spheniscus humboldti)",
    "status": "Vulnerable",
    "naturalHabitat": "Coast of Chile and Peru in South America on islands and rocky areas in burrows",
    "food": "Small fish",
    "animalInfo": "Humboldt Penguins grow to 56-70cm long and a weight of up to 4.9kg. The penguins can be distinguished by their spot patterns on their belly",
    "moreAnimalInfo": "",
    "interestingFacts": "Penguins can propel themselves at speeds up to 17 mph underwater",
    "helpfulHints": "",
    "todaysFeed": "Come and see us at Penguin Bay at 11.30am and 2.30pm - Please check around the park as these times may change"
},
{
    "zooLocation": "Otters and Reindeer",
    "animalName": "Asian Short-Clawed Otter",
    "status": "Vulnerable",
    "naturalHabitat": "Throughout a large area of Asia in wetland systems in freshwater swamps, rivers, mangroves and tidal pools",
    "food": "A variety of animals living near to the waters edge, including crabs, mussels, frogs and snails",
    "animalInfo": "Vulnerable in their natural habitat, these are the smallest species of otter in the world and are perfectly at home on land or in water. They live in extended family groups and younger family members help to raise their little brothers and sisters.",
    "moreAnimalInfo": "",
    "interestingFacts": "",
    "helpfulHints": "",
    "todaysFeed": "Come and see the otter talk and feed at our enclosure at 10.15am - Please check around the park as these times may change"
}

]

上面的例子只显示'水獭和驯鹿',因为我们只有一个TextView,它将用新值替换它,并且只显示最终的Object的zooLocation,

如果要查看所有zooLocation,请使用此活动。

package com.shifar.shifz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MyChecker extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checker);

        LinearLayout container  = (LinearLayout) findViewById(R.id.rlContainer);

        try {
            // Main Node
            JSONArray mainNode = new JSONArray(loadJSONFromAsset()); // UPDATED

            // There are 2 objects, so looping through each one
            for (int i = 0; i < mainNode.length(); i++) {

                // Collect JSONObject in ith position
                JSONObject eachObject = mainNode.getJSONObject(i);

                //Dynamically Creating,SettingText and Adding TextView
                TextView tvZooLocation = new TextView(this);
                tvZooLocation.setText(eachObject.getString("zooLocation"));
                container.addView(tvZooLocation);

            }

            // Parsing Finished

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private String loadJSONFromAsset() {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStream is = getAssets().open("animals.json");
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(is));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            bufferedReader.close();

            Log.d("X","Response Ready:"+stringBuilder.toString());

            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}

让我知道它是否有帮助。