簡體   English   中英

將數據從本地JSON文件解析為java android

[英]Parsing data from local JSON file to java android

在網上跟蹤了一些例子后,我感到很困惑,所以希望有人可以向我解釋下一步我做了什么,並指出我正確的方向。

在我的應用程序中,我創建了一個函數來加載我的資源文件夾中的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"}
]

該函數未被調用。 它只是將整個文件內容寫入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();

如何將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"
}

]

上面的例子只顯示'Otters and Reindeer',因為我們只有一個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;
    }

}

讓我知道它是否有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM