【问题标题】:Android Json parsing to ArraylistAndroid Json 解析为 Arraylist
【发布时间】:2015-07-10 09:03:37
【问题描述】:

嗨,我是 android 开发的新手,请帮我将所有 json 数据读入 android 以及如何放入 ArrayList ..这里我有 4 组问题 (4 x 4) = 16 个问题 .. 一组我有4个问题我想从集合中随机调用1个问题..请帮助我..提前谢谢

    package com.example.truefalsegame;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.SAXException;

//import com.example.jsonparser.R;



import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity 
{
    SAXParserFactory factory;
    SAXParser saxParser;
    String datas;
    String SrData = "";
    String queData = "";
    String ansData = "";
    String des;
    TextView srNo_txt, questions_txt, answer_txt;
    ImageView imageView;

    ArrayList<String> list = new ArrayList<String>();

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


        questions_txt = (TextView) findViewById(R.id.QuestionTxt);

        imageView = (ImageView)findViewById(R.id.imageView1);

        factory = SAXParserFactory.newInstance();



         try {
            saxParser = factory.newSAXParser();
            InputStream is = getAssets().open("concepts.json");

            InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br=new BufferedReader(isr);
            String str;
            StringBuffer sb=new StringBuffer();


            while((str=br.readLine())!=null)
            {


            sb = sb.append(str);
            datas =(str);
            list.add(datas);


            }

            str = sb.toString();

              JSONArray jsonarray = new JSONArray(str);

              for(int i=0; i<jsonarray.length(); i++)
              {
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String questions = obj.getString("Questions"); 
                    JSONArray question = obj.getJSONArray("Questions");
                    JSONObject ids = question.getJSONObject(0);
                    des = ids.getString("Question");

                    Log.d("hitesh", "des : "+ des );
                    //String answers = obj.getString("Answer");
                    int srno = i+1;

                    System.out.println(questions);
                    //System.out.println(answers);
                    queData += des+" \n ";


                }   

              questions_txt.setText(""+queData);





        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

    private String append(String str) {
        // TODO Auto-generated method stub
        return null;
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

这是我的 Json 文件我的 json 文件名是 (concepts.json) 并且它在 Assets 文件夹中

[
    {
        "Concept": "1",
        "Questions": [
            {
                "Question": "Carbon compounds are only straight chain compounds",
                "Answer": "F"
            },
            {
                "Question": "Carbon compounds are only cyclic compounds",
                "Answer": "F"
            },
            {
                "Question": "Carbon - Carbon linkage may form straight chain, branched chain and ring like or cyclic compounds",
                "Answer": "T"
            },
            {
                "Question": "Carbon compounds can't be cyclic compounds",
                "Answer": "F"
            }
        ]
    },
    {
        "Concept": "2",
        "Questions": [
            {
                "Question": "Saturated carbon compounds are highly reactive",
                "Answer": "F"
            },
            {
                "Question": "Unsaturated organic compounds are more reactive than saturated organic compounds",
                "Answer": "T"
            },
            {
                "Question": "Unsaturated organic compounds are less reactive than saturated organic compounds",
                "Answer": "F"
            },
            {
                "Question": "Alkanes are less reactive than alkynes",
                "Answer": "T"
            }
        ]
    },
    {
        "Concept": "3",
        "Questions": [
            {
                "Question": "Hydrocarbons contain only carbon and hydrogen",
                "Answer": "T"
            },
            {
                "Question": "Hydrocarbons contain only carbon",
                "Answer": "F"
            },
            {
                "Question": "A compound of carbon and oxygen can be hydrocarbon",
                "Answer": "F"
            },
            {
                "Question": "A compound of carbon and nitrogen can be hydrocarbon",
                "Answer": "F"
            }
        ]
    },
    {
        "Concept": "3",
        "Questions": [
            {
                "Question": "Diagram",
                "Answer": "T"
            },
            {
                "Question": "Diagram",
                "Answer": "T"
            },
            {
                "Question": "Diagram",
                "Answer": "F"
            },
            {
                "Question": "Diagram",
                "Answer": "F"
            }
        ]
    }
]

【问题讨论】:

  • Offtop:使用 GSON lib 会更好!方法很简单。
  • 您可以使用Gson library

标签: java android json arraylist


【解决方案1】:

我建议您使用Gson library 将Json 对象转换为Java 对象。然后,您可以从 List 中选择一个随机对象并将其从列表中删除(这样您选择的随机模式就不会再次选择它)。

【讨论】:

    【解决方案2】:

    我建议使用Gson Library - 这可能是处理 JSON 数据最优雅的方式。

    您需要做的就是创建模型对象来存储读取的数据,并向MainActivity 添加几行代码。以下是模型类:

    概念.java

    import java.util.List;
    
    public class Concept {
    
        private String concept;
        private List<Question> questions;
    
        // Remember to DO NOT add constructor with params when you don't have default 
        // constructor! Otherwise Gson will not be able to construct object with 
        // default constructor by using reflection mechanism.
    
        public String getConcept() {
            return concept;
        }
    
        public List<Question> getQuestions() {
            return questions;
        }
    }
    

    问题.java

    public class Question {
    
        private String question;
        private String answer;
    
        // Remember to DO NOT add constructor...
    
        public boolean getAnswer() {
            return answer != null && answer.equals("T");
        }
    
        public String getQuestion() {
            return question;
        }
    }
    

    如您所见,在方法@​​987654327@ 中有String answer 字段转换为boolean。更好的解决方案可能是在 JSON 文件中使用布尔值(即"Answer": true)。请注意,字段名称与 JSON 文件中的相同。

    当您有模型时,您需要将以下代码添加到您的MainActivity

    MainActivity.java

    import com.google.gson.FieldNamingPolicy;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.reflect.TypeToken;
    
    import java.lang.reflect.Type;
    import java.util.List;
    // some other imports...
    
    public class MainActivity extends Activity {
    
        // fields, methods, etc...
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final String fileContent = readFile();
    
            final Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                    .create();
    
            final Type collectionType = new TypeToken<List<Concept>>(){}.getType();
    
            final List<Concept> concepts = gson.fromJson(fileContent, collectionType);
            final Concept firstConcept = concepts.get(0);
            firstConcept.getConcept(); // "1"
            final Question question = firstConcept.getQuestions().get(0);
            question.getQuestion();    // "Carbon compounds are only straight chain compounds"
            question.getAnswer();      // false
    
        }
    }
    

    说明

            final Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                    .create();
    

    我们使用 builder 初始化 Gson 解析器,因为我们需要设置非默认命名策略。 UPPER_CAMEL_CASE 是大写字母开头的驼峰式。

            final Type listType = new TypeToken<List<Concept>>(){}.getType();
    
            final List<Concept> concepts = gson.fromJson(fileContent, listType);
    

    这里我们构建一个返回数据的类型。 JSON 中的根元素是数组,这就是我们使用 List 类型的原因。我们也可以使用数组类型,但列表更易于管理。 fileContentlistType 被传递给方法 fromJson,该方法解析数据并返回作为第二个参数传递的类型的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-03
      • 2017-09-05
      • 1970-01-01
      • 2023-04-09
      • 2015-08-27
      • 2021-10-31
      • 1970-01-01
      相关资源
      最近更新 更多