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

将数据从本地JSON文件解析到java android,java,android,json,Java,Android,Json,在网上看了很多例子后,我感到困惑,希望有人能向我解释下一步该做什么,并为我指明正确的方向 在我的应用程序中,我创建了一个函数来加载JSON文件,该文件位于我的资产文件夹中 public String loadJSONFromAsset() { String json = null; try { InputStream is = getAssets().open("animals.json"); int size = is.available()

在网上看了很多例子后,我感到困惑,希望有人能向我解释下一步该做什么,并为我指明正确的方向

在我的应用程序中,我创建了一个函数来加载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"}
]

未调用该函数。它只将整个文件内容写入字符串,但不创建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:

因此,要在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();
    }
编辑2: 干净利落

MyChecker.java

上面的示例将只显示“水獭和驯鹿”,因为我们只有一个TextView,它将用新值替换它,并且只显示最终对象的缩放位置

如果要查看所有缩放位置,请使用此活动

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

}
package com.shifar.shifz;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.LinearLayout;
导入android.widget.TextView;
公共类MyChecker扩展活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.checker);
LinearLayout容器=(LinearLayout)findViewById(R.id.rlContainer);
试一试{
//主节点
JSONArray mainNode=新的JSONArray(loadJSONFromAsset());//已更新
//有2个对象,因此循环通过每个对象
对于(int i=0;i

如果有帮助,请告诉我。

显示从文件读取的json字符串,你想知道如何解析json并将值放入TextView,不是吗?目前只是在TextView中是的,那么我如何从obj提取信息?这仍然是我的主要查询所在。你上面给出的代码与我尝试的另一个版本类似在这一点上,t仍然丢失。因此,在本例中,您的上层是一个JSONArray,因此您应该用JSONArray替换JSONObject的所有外观。然后您可以通过检查我附加的文档来检索元素。抱歉,我仍然感到困惑。因此,我得到的是JSONArray而不是JSONObject。因此JSONArray obj=loadJSONFromAsset();正在将JSON加载到数组中吗?那么我想访问这些值吗?检查文档:即通过访问JSONObject j1=jsonArray.get(0)获取第一个键;然后ie String location=j1.get(“zooLocation”);等等。因此,使用jsonArray obj=loadJSONFromAsset();然后我将执行jsonArray mainNode=new jsonArray(obj)?不,在我看来,如果loadJSONFromAsset()返回字符串会更好。然后您可以调用JSONArrar jArray=new JSONArray(loadJSONFromAsset());并像我一样执行其余操作。答案更新为@wegsehen的loadJSONFromAsset()模式版本。谢谢wegsehen,您节省了我的时间:)JSONArray obj=new JSONArray(loadJSONFromAsset());我之前尝试过,但它给出了一个错误“Unhandled Exception:org.json.JSONException”,该错误使用了我最初的方法,然后调用它。您是否检查了更新的答案?
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;
    }

}
    <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>
[
{
    "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"
}

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

}