【问题标题】:How to pase local JSON and populate a RecyclerView?如何解析本地 JSON 并填充 RecyclerView?
【发布时间】:2017-03-22 15:54:32
【问题描述】:

我对如何解析本地 Json 感到困惑。我尝试了很多,但我找不到解决方案。
我想填充一个仅包含一个简单标题的 ArrayList - 我想将该 tite 从 JSON 添加到 RecylerView。

{
    "hollywood": [{
        "_id": "58d3264f93f24d2bc87bebf5",
        "title": "sagar rana",
        "image": "encrypted-tbn1.gstatic.com/...",
        "genre": "hollywood",
        "description": "This for only demo purpose",
        "release": 2010,
        "download": "No download",
        "youtube": "youtube.com/embed/C-5EOd8xavw...",
        "__v ": 0,
        "upload ": "2017-03-23T01:35:11.182Z"
    }]
}

MainActivty.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

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

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

import static android.R.attr.data;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    MyAdapter recycleradapter;
    private ArrayList<Moviedemo> mArrayList;

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

        try {
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray m_jArry = obj.getJSONArray("hollywood");
            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("hollywood"));
                String formula_value = jo_inside.getString("hollywood");
                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();
        }
        recycleradapter = new MyAdapter(mArrayList);
        recyclerView.setAdapter(recycleradapter);

        recyclerViewstart();
        loadJSONFromAsset();


    }

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

            InputStream is = getAssets().open("homepage.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;


    }

    private void recyclerViewstart() {
        recyclerView=(RecyclerView)findViewById(R.id.recylce);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

    }
}

【问题讨论】:

  • { "hollywood": [ { "_id": "58d3264f93f24d2bc87bebf5", "title": "sagar rana", "image": "encrypted-tbn1.gstatic.com/…", "genre": "hollywood", “description”:“仅用于演示目的”,“release”:“2010”,“download”:“无下载”,“youtube”:“youtube.com/embed/C-5EOd8xavw”,“__v”:0,“upload”:“ 2017-03-23T01:35:11.182Z"}]
  • 可以使用Gson解析json
  • @BhupinderSingh 将其添加为帖子而不是评论
  • 我是 json 新手
  • JSON 没那么难,那么这段代码到底哪里出了问题?

标签: android json android-recyclerview


【解决方案1】:

所以这是你的适配器。

recycleradapter = new MyAdapter(mArrayList);
recyclerView.setAdapter(recycleradapter);

你从未初始化过mArrayList...所以先这样做

mArrayList = new ArrayList<Moviedemo>();

然后,您需要添加到该列表以确定要在 JSON 中解析的内容。

您已经展示了如何获取数组和字符串。

我想将 json 中的标题添加到 recyler 视图中

只是标题?作为字符串?那为什么适配器会持有整个Moviedemo 对象呢?

// Set the adapter
recycleradapter = new MyAdapter(mArrayList);
recyclerView.setAdapter(recycleradapter);

// Open and parse file
try {
    JSONObject obj = new JSONObject(loadJSONFromAsset());
    JSONArray m_jArry = obj.getJSONArray("hollywood");

    for (int i = 0; i < m_jArry.length(); i++) {
        // Start an object
        Moviedemo movie = new Moviedemo();

        // Parse the JSON
        JSONObject jo_inside = m_jArry.getJSONObject(i);
        String title = jo_inside.getString("title");

        // Build the object
        movie.setTitle(title);

        // Add the object to the list
        mArrayList.add(movie);
    }

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

// Update adapter
recycleradapter.notifyDataSetChanged();

【讨论】:

    【解决方案2】:

    正如here 所示,应该这样做:

    StringBuilder buf = new StringBuilder();
    InputStream json = getAssets().open("book/contents.json");
    BufferedReader in =
        new BufferedReader(new InputStreamReader(json, "UTF-8"));
    String str;
    
    while ((str=in.readLine()) != null) {
      buf.append(str);
    }
    
    in.close();
    

    你可以做这样的事情来解析它:

    JSONObject object = new JSONObject(jsonString);
    

    使用org.jsonlibrary,可以找到here

    【讨论】:

    【解决方案3】:

    试试这个简单的方法

        private JSONObject getAssetJSON() {
            String inFile = "fileName.json";
            JSONObject assetJson = null;
            try {
                InputStream stream = context.getAssets().open(inFile);
                int size = stream.available();
                byte[] buffer = new byte[size];
                stream.read(buffer);
                stream.close();
                String assetString = new String(buffer);
                assetJson = new JSONObject(assetString);
            } catch (IOException e) {
                // Handle IO exceptions here
            } catch (JSONException e) {
                // Handle JSON exceptions here
            }
           return assetJson;
       }
    

    【讨论】:

      【解决方案4】:

      处理 JSON 是任何 Android 应用程序最重要的一步。 根据我的建议,请尝试了解 GSON 库。

      这些是一些有用的链接,您可以更好地了解它。 1. this , 2.this

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-04
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多