简体   繁体   中英

Parsing data from local JSON file to java android

After following a number of examples online, I've got confused so rather hope someone can explain to me what I do next and point me in the right direction.

Within my app, I've created a function to load my JSON file, which is in my assets folder.

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;

}

So then in onCreate, I have the following line

JSONObject obj = new JSONObject();

I'm quite confused as to how this is calling the loadJSONFromAsset(), as other examples I had seen did this, but this was the approach that I understood, until I got to here. For example, how would I output the JSON into a TextView I have created?

Thanks

Edit - Sorry forgot the 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"}
]

The function is not being called. It just writes the whole file content to a String but does not create a JSONObject. With the line you wrote, you just create a new empty JSONObject .

So what you really want to do is this:

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;
}

Now you can use the JSONObject via the standard methods:

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

So to have the JSONObject in your onCreate method, you would simply do a:

JSONObject obj = loadJSONFromAsset();

how would I output the JSON into a TextView I have created?

From the given JSON, it's a JSON Array because it's starting with [ , if the response start with { then it'll be a JSON Object.

So let's parse the 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();
    }

UPDATED

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; 
}

EDIT 2: With Complete Activity

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;
    }

}

layout/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>

assets/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"
}

]

The above example will only show 'Otters and Reindeer' because we have only one TextView and it will replace it with new value and shows only the final Object's zooLocation,

if you want see all zooLocation then use this activity this.

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;
    }

}

let me know if it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM