首页 > 程序开发 > 移动开发 > 其他 >

Json数据解析“编程开发”

2017-10-09

Json数据解析“编程开发”。

首先使用API接口:

对应的json数据:

{
    "count":20,
    "start":0,
    "total":641,
    "books":[
        {
            "id":"4866934",
            "title":"Python基础教程"
        },
        {
            "id":"3117898",
            "title":"Python源码剖析"
        },
        {
            "id":"3948354",
            "title":"Python学习手册"
        },
        {
            "id":"3884108",
            "title":"可爱的Python"
        },
        …
        ]
}

然后建立Android 工程JsonDemo:

添加FastJson、Gson、Volley的gradle依赖:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.alibaba:fastjson:1.2.38'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
}

添加权限:

    

布局设置:

主布局activity_main.xml:




    


子布局item.xml:



    


javaBean类Book.java:

package com.example.dpl.jsondemo.bean;

/**
 * Created by dpl on 2017/10/4 0004.
 */

public class Book {
    private String id;
    private String title;

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}
适配器设置BookListAdapter.java:
package com.example.dpl.jsondemo.Adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.dpl.jsondemo.R;
import com.example.dpl.jsondemo.bean.Book;

import java.util.ArrayList;

/**
 * Created by dpl on 2017/10/4 0004.
 */

public class BookListAdapter extends BaseAdapter {
    private Context context1;
    private ArrayList list;
    public BookListAdapter(Context context, ArrayList books){
        this.context1=context;
        this.list=books;
    }
    @Override
    public int getCount() {
        return list.size();
    }

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

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

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder holder=null;
        if(holder==null){
            view=View.inflate(context1, R.layout.item,null);
            holder=new ViewHolder();
            holder.textView=view.findViewById(R.id.tv);
            view.setTag(holder);
        }else {
            holder= (ViewHolder) view.getTag();
        }
        Book book=list.get(position);
        holder.textView.setText(book.getTitle()+"\n"+book.getId());
        return view;
    }
    class ViewHolder{
        TextView textView;
    }
}

MainActivity.java类:
import com.example.dpl.jsondemo.Adapter.BookListAdapter;
import com.example.dpl.jsondemo.bean.Book;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

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

import java.lang.reflect.Type;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private String url="https://api.douban.com/v2/book/search?q=python&fields=id,title";
    private ListView lv;
    private BookListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv= (ListView) findViewById(R.id.lv);
        getData();

    }

    private void getData() {
        StringRequest request=new StringRequest(url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                Log.i("info",response);
                try {
                    dealData(response);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        new Volley().newRequestQueue(getApplicationContext()).add(request);
    }

    private void dealData(String response) throws JSONException {
//        Gson gson=new Gson();
//        Type listType=new TypeToken>(){}.getType();
        //TypeToken的使用非常简单,如上面的代码,只要将需要获取类型的泛型类作为TypeToken的泛型参数构造一个匿名的
        // 子类,就可以通过getType()方法获取到我们使用的泛型类的泛型参数类型
        JSONObject object=new JSONObject(response);
        //字符串json获得JSONObject对象
//        ArrayList books=gson.fromJson(object.getString("books"),listType);//books为标签(获取的
        //内容是标签内的,Gson库的使用
        ArrayList books= (ArrayList) JSON.parseArray(object.getString("books")
                ,Book.class);//fastJson库的使用,将json格式的数据转换成数组格式
        adapter=new BookListAdapter(this,books);
        lv.setAdapter(adapter);//添加到ListView上
    }
}

运行效果:\

相关文章
最新文章
热点推荐