【问题标题】:Retrieving .json file from assets and Parsing从资产和解析中检索 .json 文件
【发布时间】:2014-05-08 05:58:01
【问题描述】:

我正在尝试检索我在 assets 中生成的 .json 文件以测试我的 ListView ,我在运行 try/catch 的应用程序时遇到了问题总是返回异常并且文件永远不会加载,ListView 返回 "No data" ,这是我的代码

请注意这个类扩展了 FragmentList

public View onCreateView( LayoutInflater inflater, 
        ViewGroup container,
        Bundle savedInstanceState )
    {


        View view = inflater.inflate(R.layout.frag1, container, false);
        try {
            obj =  new JSONObject(loadJSONFromAsset("Questions.json"));
            JSONArray m_jArry = obj.getJSONArray("Questions");
            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);

                  String Created_At = jo_inside.getString("Created At");
                  String Asker_Name = jo_inside.getString("Asker_Name");
                  String Question_Title = jo_inside.getString("QuestionTitle");
                  String Question_Body = jo_inside.getString("QuestionBody");
                  String Question_Id = jo_inside.getString("Question_Id");
                  Question question = new Question(Asker_Name, Question_Title, Question_Body, Created_At);
                  questions.add(question);

              //Add your values in your `ArrayList` as below:

             m_li=new HashMap<String, String>();
             m_li.put("Created At", Created_At );
             m_li.put("Asker_Name", Asker_Name );
             m_li.put("QuestionTitle", Question_Title);
             m_li.put("QuestionBody", Question_Body );
             m_li.put("Question_Id", Question_Id );

             formList.add(m_li);
               //Same way for other value...
              }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

这是loadJSONFromAsset的方法

public String loadJSONFromAsset(String path) {
    String json = null;
    try {
    InputStream is = getActivity().getAssets().open(path);

    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;

}

【问题讨论】:

    标签: android json listview android-fragments android-assets


    【解决方案1】:

    我已成功处理 res/raw 文件夹中的 json 文件(从未在资产中尝试过)。如果这是您的选择,请尝试以下代码:

    InputStream in_s = res.openRawResource(R.raw.yourfile);
    byte[] b = new byte[in_s.available()];
    in_s.read(b);
    json = new String(b);
    JSONObject obj = new JSONObject(json);
    

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2017-11-02
      • 2019-08-13
      • 2012-05-22
      • 2012-06-16
      相关资源
      最近更新 更多