简体   繁体   English

Android Json解析为Arraylist

[英]Android Json parsing to Arraylist

Hi Guys im new in android development please help me to read all json data in to android and how to put in ArrayList ..here i have 4 set of questions (4 x 4) = 16 questions .. in one set i have 4 question i want to call 1 question randomly from set .. please help me .. Thanks in advance 嗨,大家好,我是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);
    }
}

Here is my Json file My jsonfile name is (concepts.json) and its in Assets folder 这是我的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"
            }
        ]
    }
]

I would recommend you to use the Gson library to transform the Json object to Java object. 我建议您使用Gson库将Json对象转换为Java对象。 Then, you can choose a random object from the List<> and remove it from the list (so your random mode of choice wouldn't chose it again). 然后,您可以从List <>中选择一个随机对象,然后将其从列表中删除(因此您选择的随机模式不会再次选择它)。

I recommend to use Gson Library - it's probably most elegant way to deal with JSON data. 我建议使用Gson库 -这可能是处理JSON数据的最优雅的方式。

All you need to do is create your model objects to store your read data and add a couple of lines to MainActivity . 您需要做的就是创建模型对象以存储读取的数据,并向MainActivity添加几行。 Here are model classes: 这是模型类:

Concept.java Concept.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;
    }
}

Question.java Question.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;
    }
}

As you can see, there is String answer field converted to boolean in method getAnswer . 如您所见,方法getAnswerString answer字段转换为boolean Better solution might be to use boolean values in your JSON file (ie "Answer": true ). 更好的解决方案可能是在JSON文件中使用布尔值(即"Answer": true )。 Please notice that field names are the same as in JSON file. 请注意,字段名称与JSON文件中的相同。

When you have model, you need to add the following code to your MainActivity : 建立模型后,需要将以下代码添加到MainActivity

MainActivity.java 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

    }
}

Explanation 说明

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

We initialise our Gson parser using builder, because we need to set non-default naming policy. 我们使用构建器初始化Gson解析器,因为我们需要设置非默认的命名策略。 UPPER_CAMEL_CASE is camel case starting with upper letter. UPPER_CAMEL_CASE是驼峰式大写字母。

        final Type listType = new TypeToken<List<Concept>>(){}.getType();

        final List<Concept> concepts = gson.fromJson(fileContent, listType);

Here we build a type of returned data. 在这里,我们建立了一种返回的数据。 Root element in your JSON is array that's why we use List type. JSON中的Root元素是数组,这就是我们使用List类型的原因。 We also could use array type, but lists are easier to manage. 我们也可以使用数组类型,但是列表更易于管理。 fileContent and listType are passed to method fromJson which parses data and returns result of type passed as second parameter. fileContentlistType传递给fromJson方法,该方法解析数据并返回作为第二个参数传递的类型的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM