使用JSON解析数据创建新对象

时间:2018-02-18 11:08:06

标签: java android json

我正在练习JSON。我正在使用新闻api,我只检索新闻的名称,作者和标题。 我使用NewsModel java类来保存新闻。我可以手动将数据添加到此类并显示在列表视图中。

我正在成功解析,但我无法成功地将新闻数据添加到我的模型类中。

这是我的MainActivity(解析和向模型类添加数据)

public class MainActivity extends AppCompatActivity {

public TextView textView_parse;
private Button button_parse, button_list;
public NewsModel newsModel;
public double temp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //
    textView_parse = (TextView)findViewById(R.id.textView_parse);
    button_parse = (Button) findViewById(R.id.button_parse);
    button_list = (Button)findViewById(R.id.button_list);
    //

    button_parse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            new JSONParsing().execute("https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey=b1ed0a1fd9ca444fa9a9dd52b754fc6b");

        }
    });

    button_list.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this, NewsListActivity.class));
        }
    });
}

private class JSONParsing extends AsyncTask<String, String, String>{


    @Override
    protected String doInBackground(String... strings) {

        HttpURLConnection httpURLConnection = null;
        BufferedReader bufferedReader = null;

        try{
            URL url = new URL(strings[0]);
            httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.connect();

            InputStream stream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";

            while((line = bufferedReader.readLine()) != null){
                stringBuffer.append(line);
            }

            String finalJson = stringBuffer.toString();

            StringBuffer finalBuffer = new StringBuffer();
            JSONObject jsonObject = new JSONObject(finalJson);
            JSONArray parentArray = jsonObject.getJSONArray("articles");



            for(int i=0; i<parentArray.length(); i++){

                JSONObject parentObject = parentArray.getJSONObject(i);
                JSONObject secondObject = parentObject.getJSONObject("source");
                String name = secondObject.getString("name");
                String author = parentObject.getString("author");
                String title = parentObject.getString("title");

                newsModel = new NewsModel(name,author,title,i);
                finalBuffer.append("Name: "+name+"\n\n"+ "Author: "+author+ "\n\n"+ "Title: "+title+"\n\n\n\n");

            }

            /* tek çekim
            JSONObject parentObject = parentArray.getJSONObject(0);
            String title = parentObject.getString("title");
            */


            return finalBuffer.toString();

        }catch (IOException e){
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return null;

    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        textView_parse.setText(s);

    }
}

}

这是我的模型类;

public class NewsModel {
String name;
String author;
String title;
int id;

public NewsModel(){}

public NewsModel(String name, String author, String title, int id) {
    this.name = name;
    this.author = author;
    this.title = title;
    this.id=id;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

}

这是我的适配器类;

public class Adapter_NewsList extends BaseAdapter {

private Context mContext;
public List<NewsModel> mNewsList;

public Adapter_NewsList(Context mContext, List<NewsModel> mNewsList) {
    this.mContext = mContext;
    this.mNewsList = mNewsList;
}

@Override
public int getCount() {
    return mNewsList.size();
}

@Override
public Object getItem(int i) {
    return mNewsList.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    View myView = View.inflate(mContext, R.layout.item_news_list,null);
    TextView textView_name = (TextView)myView.findViewById(R.id.textView_name);
    TextView textView_author = (TextView)myView.findViewById(R.id.textView_author);
    TextView textView_title = (TextView)myView.findViewById(R.id.textView_title);

    textView_name.setText(mNewsList.get(i).getName());
    textView_author.setText(mNewsList.get(i).getAuthor());
    textView_title.setText(mNewsList.get(i).getTitle());

    myView.setTag(mNewsList.get(i).getId());

    return myView;
}

}

3 个答案:

答案 0 :(得分:0)

您必须在列表中存储可以转发到适配器的对象

public class MainActivity extends AppCompatActivity {

public TextView textView_parse;
private Button button_parse, button_list;
public NewsModel newsModel;
public double temp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //
    textView_parse = (TextView)findViewById(R.id.textView_parse);
    button_parse = (Button) findViewById(R.id.button_parse);
    button_list = (Button)findViewById(R.id.button_list);
    //

    button_parse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            new JSONParsing().execute("https://newsapi.org/v2/top-headlines?sources=abc-news&apiKey=b1ed0a1fd9ca444fa9a9dd52b754fc6b");

        }
    });

    button_list.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this, NewsListActivity.class));
        }
    });
}

private class JSONParsing extends AsyncTask<String, String, String>{


    @Override
    protected String doInBackground(String... strings) {

        HttpURLConnection httpURLConnection = null;
        BufferedReader bufferedReader = null;
        ArrayList<NewsModel> newsModels = new ArrayList<>(); //create a list

        try{
            URL url = new URL(strings[0]);
            httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.connect();

            InputStream stream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";

            while((line = bufferedReader.readLine()) != null){
                stringBuffer.append(line);
            }

            String finalJson = stringBuffer.toString();

            StringBuffer finalBuffer = new StringBuffer();
            JSONObject jsonObject = new JSONObject(finalJson);
            JSONArray parentArray = jsonObject.getJSONArray("articles");



            for(int i=0; i<parentArray.length(); i++){

                JSONObject parentObject = parentArray.getJSONObject(i);
                JSONObject secondObject = parentObject.getJSONObject("source");
                String name = secondObject.getString("name");
                String author = parentObject.getString("author");
                String title = parentObject.getString("title");

                newsModel = new NewsModel(name,author,title,i);
                newsModels.add(newsModel); //keep storing model object in list
                finalBuffer.append("Name: "+name+"\n\n"+ "Author: "+author+ "\n\n"+ "Title: "+title+"\n\n\n\n");

            }

            /* tek çekim
            JSONObject parentObject = parentArray.getJSONObject(0);
            String title = parentObject.getString("title");
            */


            return finalBuffer.toString(); //return list here and use that in adapter

        }catch (IOException e){
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return null;

    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        textView_parse.setText(s);

    }
}

答案 1 :(得分:0)

的ArrayList&LT; NewsModel&gt; newsmodel = new ArrayList&lt;&gt;();

newsmodel = new Gson()。fromJson(parentArray.toString(),                                                 new TypeToken&gt;(){}。getType());

试试这个可能对你有用,对我有用。

答案 2 :(得分:0)

作为@ architjn的答案,经过一些修改。

替换

AsyncTask<String, String, String>

AsyncTask<String, String, ArrayList<NewsModel>>

然后更新覆盖功能,如下所示

private class JSONParsing extends AsyncTask<String, String, ArrayList<NewsModel>> {


    @Override
    protected ArrayList<NewsModel> doInBackground(String... strings) {

        HttpURLConnection httpURLConnection = null;
        BufferedReader bufferedReader = null;
        ArrayList<NewsModel> newsModels = new ArrayList<>(); //create a list
        NewsModel newsModel = null; 

        try {
            URL url = new URL(strings[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();

            InputStream stream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer stringBuffer = new StringBuffer();
            String line = "";

            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }

            String finalJson = stringBuffer.toString();

            StringBuffer finalBuffer = new StringBuffer();
            JSONObject jsonObject = new JSONObject(finalJson);
            JSONArray parentArray = jsonObject.getJSONArray("articles");


            for (int i = 0; i < parentArray.length(); i++) {

                JSONObject parentObject = parentArray.getJSONObject(i);
                JSONObject secondObject = parentObject.getJSONObject("source");
                String name = secondObject.getString("name");
                String author = parentObject.getString("author");
                String title = parentObject.getString("title");

                newsModel = new NewsModel(name, author, title, i);
                newsModels.add(newsModel); //keep storing model object in list
                finalBuffer.append("Name: " + name + "\n\n" + "Author: " + author + "\n\n" + "Title: " + title + "\n\n\n\n");

            }

        /* tek çekim
        JSONObject parentObject = parentArray.getJSONObject(0);
        String title = parentObject.getString("title");
        */


            return newsModels; //return list here and use that in adapter

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return null;

    }

    @Override
    protected void onPostExecute(ArrayList<NewsModel> resultList) {
        super.onPostExecute(resultList);
        //set up the adapter with resultList
    }
}

毕竟,您可以使用 resultList 参数在 onPostExecute(ArrayList resultList)方法中将列表设置为适配器,祝您好运。