it-swarm.dev

Android Java;如何将资产文件夹中的本地JSON文件解析为ListView

我正在开发一个物理应用程序,它应该显示一个公式列表,甚至解决其中的一些(唯一的问题是ListView

这是我的主要布局

    <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:measureWithLargestChild="false"
    Android:orientation="vertical"
    tools:context=".CatList" >


    <RelativeLayout
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:background="@drawable/titlebar" >

        <TextView
            Android:id="@+id/Title1"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:layout_centerHorizontal="true"
            Android:layout_centerVertical="true"
            Android:text="@string/app_name"
            Android:textAppearance="?android:attr/textAppearanceLarge"
            Android:textColor="#ff1c00"
            Android:textIsSelectable="false" />

    </RelativeLayout>

    <ListView
        Android:id="@+id/listFormulas"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content" >

    </ListView>

</LinearLayout>

这是我的主要活动

package com.wildsushii.quickphysics;

import Java.io.IOException;
import Java.io.InputStream;
import Java.util.ArrayList;
import Java.util.HashMap;

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

import Android.os.Bundle;
import Android.app.Activity;
import Android.content.Context;
import Android.content.res.AssetManager;
import Android.view.Menu;
import Android.widget.ListView;

public class CatList extends Activity {



    public static String AssetJSONFile (String filename, Context context) throws IOException {
        AssetManager manager = context.getAssets();
        InputStream file = manager.open(filename);
        byte[] formArray = new byte[file.available()];
        file.read(formArray);
        file.close();

        return new String(formArray);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cat_list);
        ListView categoriesL = (ListView)findViewById(R.id.listFormulas);

        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        Context context = null;
        try {
            String jsonLocation = AssetJSONFile("formules.json", context);
            JSONObject formArray = (new JSONObject()).getJSONObject("formules");
            String formule = formArray.getString("formule");
            String url = formArray.getString("url");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //My problem is here!!
    }


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

我实际上知道我可以在不使用JSON的情况下实现这一点,但我需要更多练习解析JSON。顺便说一句,这是JSON

    {
    "formules": [
    {
      "formule": "Linear Motion",
      "url": "qp1"
    },
    {
      "formule": "Constant Acceleration Motion",
      "url": "qp2"
    },
    {
      "formule": "Projectile Motion",
      "url": "qp3"
    },
    {
      "formule": "Force",
      "url": "qp4"
    },
    {
      "formule": "Work, Power, Energy",
      "url": "qp5"
    },
    {
      "formule": "Rotary Motion",
      "url": "qp6"
    },
    {
      "formule": "Harmonic Motion",
      "url": "qp7"
    },
    {
      "formule": "Gravity",
      "url": "qp8"
    },
    {
      "formule": "Lateral and Longitudinal Waves",
      "url": "qp9"
    },
    {
      "formule": "Sound Waves",
      "url": "qp10"
    },
    {
      "formule": "Electrostatics",
      "url": "qp11"
    },
    {
      "formule": "Direct Current",
      "url": "qp12"
    },
    {
      "formule": "Magnetic Field",
      "url": "qp13"
    },
    {
      "formule": "Alternating Current",
      "url": "qp14"
    },
    {
      "formule": "Thermodynamics",
      "url": "qp15"
    },
    {
      "formule": "Hydrogen Atom",
      "url": "qp16"
    },
    {
      "formule": "Optics",
      "url": "qp17"
    },
    {
      "formule": "Modern Physics",
      "url": "qp18"
    },
    {
      "formule": "Hydrostatics",
      "url": "qp19"
    },
    {
      "formule": "Astronomy",
      "url": "qp20"
    }
  ]
}

我尝试了很多东西,甚至删除整个项目来制作一个新的:(

144
theWildSushii

正如Faizan在 他们的答案在这里 中描述的那样:

首先使用下面的代码从你的assests文件中读取Json文件。

然后你可以通过这个函数简单地读取这个字符串返回

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.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;
}

并使用这种方法

    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

有关JSON 阅读此处 的更多详细信息

287
GrIsHu
{ // json object node
    "formules": [ // json array formules
    { // json object 
      "formule": "Linear Motion", // string
      "url": "qp1"
    }

你在做什么

  Context context = null; // context is null 
    try {
        String jsonLocation = AssetJSONFile("formules.json", context);

所以改为

   try {
        String jsonLocation = AssetJSONFile("formules.json", CatList.this);

要解析

我相信你从assests文件夹中获取字符串。

try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
        e.printStackTrace();
} catch (JSONException e) {
        e.printStackTrace();
}
10
Raghunandan

从Assets文件夹中读取JSON文件并作为字符串对象返回的方法。

public static String getAssetJsonData(Context context) {
            String json = null;
            try {
                InputStream is = context.getAssets().open("myJson.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;
            }

            Log.e("data", json);
            return json;

        }

现在解析您的活动中的数据: -

String data = getAssetJsonData(getApplicationContext());
        Type type = new TypeToken<Your Data model>() {
        }.getType();
  <Your Data model> modelObject = new Gson().fromJson(data, type);
5
Anil Singhania

使用Kotlin有这个扩展函数来读取文件返回为字符串。

fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

使用任何JSON解析器解析输出字符串。

2
Libin

使用 _ okio _

public static String readFileFromAssets(Context context, String fileName) {

            try {
                InputStream input = context.getAssets().open(fileName);
                BufferedSource source = Okio.buffer(Okio.source(input));
                return source.readByteString().string(Charset.forName("utf-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
    }

然后...

String data = readFileFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json
        Type reviewType = new TypeToken<List<Object>>() {
}.getType();
Object object = new Gson().fromJson(data, reviewType);
0
Williaan Lopes