Gson解析/JSON解析/新建

创建查看
https://blog.csdn.net/u013005791/article/details/72904217

 @Override
                    public void onComplete(Object response) {
                        Log.e("tag", "onComplete: "+response);
                        JSONObject obj = (JSONObject) response;

什么是Gson?

Gson 是Google解析Json的一个开源框架,同类的框架还有fastJson、JackJson等等。

怎么实例化?

Gson gson = new Gson();或者Gson gson = new GsonBuilder().create();

把要解析的文件复制到assets
如果乱码看一下你的txt编码格式是否是UTF-8的
TypeToken是gson提供的数据类型转换器

my

package com.example.wangye.androidgj_class9;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    Gson gson;
    String json;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gson = new Gson();
        getDataByAssets();
        News news = gson.fromJson(json,News.class);
        for (int i = 0; i < news.getResult().size(); i++) {
            Log.d("title",news.getResult().get(i).getTitle());
        }
    }

    public void getDataByAssets(){
        try {
//可以此方法来加载assets里面的data.txt获得输入流
//然后通过ByteArrayOutputStream的字节输出流.tostring返回Json的代码格式
            InputStream is = getAssets().open("data.txt");
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            byte buffer[] = new byte[512];
            int length = -1;
            while( ( length = is.read(buffer) ) != -1){
                bs.write(buffer,0,length);
                bs.flush();
            }
            is.close();
            bs.close();
            json = bs.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

想下载一个GsonFormat的插件


Gson解析/JSON解析/新建_第1张图片
360截图20180710201627322.jpg

然后可以按快捷键Alt+s跳出框,输入Json的数据


Gson解析/JSON解析/新建_第2张图片
360截图20180710201139953.jpg

生成数据要建一个Bean类
News
package com.example.wangye.androidgj_class9;

import java.util.List;

/**
 * Created by wangye on 2018/7/10.
 */

public class News {

    /**
     * reason : 查询成功
     * result : [{"title":"从《超时空同居》到《药神》,徐峥一年押中4个"爆款"将净赚超6亿?","content":"红利大头落在了《超时空同居<\/em>》身上。光线为《超时空同居<\/em>》进行了5亿保底,而这部电影也拥有着黑马电影的标配:新人导演(青年导演苏伦)、低成本(制作成本3000万、宣发费用1500万)、"无流量"演员(佟丽娅、雷佳音)、喜剧爱情题材,最终该电影最终票房达到8.98亿,片方票...","img_width":"","full_title":"从《超时空同居》到《药神》,徐峥一年押中4个"爆款"将净赚超6亿?","pdate":"2小时前","src":"顶尖财经网","img_length":"","img":"","url":null,"pdate_src":"2018-07-09 13:36:02"},{"title":"《超时空同居》百度云分享BD1080P高清中字迅雷云盘完整资源下载","content":"抛开可笑的奇幻逻辑架构,爱情的部分还挺好看的。两个演员讨喜舒服,自然而然的甜,居然还看哭了0.1秒。听工作人员说导演原本是想拍两个人同居<\/em>的过程中日久生情的,雷佳音说:"不是啊,直男看到那么漂亮的女孩肯定是一秒就喜欢了啊。"哈哈哈哈。 一部完成度非常高的商业...","img_width":"249","full_title":"《超时空同居》百度云分享BD1080P高清中字迅雷云盘完整资源下载","pdate":"07月8日 11:24","src":"今日头条","img_length":"496","img":"http://p8.qhimg.com/t0109d3eefc7a505592.jpg","url":null,"pdate_src":"2018-07-08 11:24:52"},{"title":"《超时空同居》百度云网盘BD1080P高清中字迅雷云盘完整资源下载","content":"pan.baidu.com/s/1p5rhmWXc_C2YRIbu4LmrCg 密码:u17g pan.baidu.com/s/1M2NnO0KhIdrKEzfHfyOkbg 密码:3hkm 这部电影但凡是换个雷佳音以外的人演都算完了,雷佳音确实是把男主演得蛮可爱的。但女性角色啊\u2026我现在怀疑以徐峥为代表的这类中年男子只承认世界上有三种女性...","img_width":"367","full_title":"《超时空同居》百度云网盘BD1080P高清中字迅雷云盘完整资源下载","pdate":"07月8日 11:22","src":"今日头条","img_length":"550","img":"http://p1.qhimg.com/t013dd1fc08ba3469e6.jpg","url":null,"pdate_src":"2018-07-08 11:22:30"},{"title":"《超时空同居》,物质和爱情你该如何选择?","content":"《超时空同居<\/em>》由苏伦导演、徐峥监制,雷佳音、佟丽娅、张衣领衔主演的奇幻喜剧片 。讲述了失意女青年谷小焦因一个突如其来的意外,不得不与陆鸣开启同居生活的故事 。 剧情讲述了2018年的美女谷小焦(佟丽娅饰)与1999年的失意男陆鸣(雷佳音饰),一觉醒来时空发生重叠两人睡在...","img_width":"427","full_title":"《超时空同居》,物质和爱情你该如何选择?","pdate":"07月8日 11:02","src":"快资讯","img_length":"640","img":"http://p8.qhimg.com/t0139ffb91830857c6e.jpg","url":null,"pdate_src":"2018-07-08 11:02:00"}]
     * error_code : 0
     */

    private String reason;
    private int error_code;
    private List result;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public int getError_code() {
        return error_code;
    }

    public void setError_code(int error_code) {
        this.error_code = error_code;
    }

    public List getResult() {
        return result;
    }

    public void setResult(List result) {
        this.result = result;
    }

    public static class ResultBean {
        /**
         * title : 从《超时空同居》到《药神》,徐峥一年押中4个"爆款"将净赚超6亿?
         * content : 红利大头落在了《超时空同居》身上。光线为《超时空同居》进行了5亿保底,而这部电影也拥有着黑马电影的标配:新人导演(青年导演苏伦)、低成本(制作成本3000万、宣发费用1500万)、"无流量"演员(佟丽娅、雷佳音)、喜剧爱情题材,最终该电影最终票房达到8.98亿,片方票...
         * img_width :
         * full_title : 从《超时空同居》到《药神》,徐峥一年押中4个"爆款"将净赚超6亿?
         * pdate : 2小时前
         * src : 顶尖财经网
         * img_length :
         * img :
         * url : null
         * pdate_src : 2018-07-09 13:36:02
         */

        private String title;
        private String content;
        private String img_width;
        private String full_title;
        private String pdate;
        private String src;
        private String img_length;
        private String img;
        private Object url;
        private String pdate_src;

        public String getTitle() {
            return title;
        }

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

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getImg_width() {
            return img_width;
        }

        public void setImg_width(String img_width) {
            this.img_width = img_width;
        }

        public String getFull_title() {
            return full_title;
        }

        public void setFull_title(String full_title) {
            this.full_title = full_title;
        }

        public String getPdate() {
            return pdate;
        }

        public void setPdate(String pdate) {
            this.pdate = pdate;
        }

        public String getSrc() {
            return src;
        }

        public void setSrc(String src) {
            this.src = src;
        }

        public String getImg_length() {
            return img_length;
        }

        public void setImg_length(String img_length) {
            this.img_length = img_length;
        }

        public String getImg() {
            return img;
        }

        public void setImg(String img) {
            this.img = img;
        }

        public Object getUrl() {
            return url;
        }

        public void setUrl(Object url) {
            this.url = url;
        }

        public String getPdate_src() {
            return pdate_src;
        }

        public void setPdate_src(String pdate_src) {
            this.pdate_src = pdate_src;
        }
    }
}

补全

package com.example.gson_text;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Button GsonButton;
    private TextView textView;
    private Button JsonButton;
    private String mJSONdata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GsonButton = (Button) findViewById(R.id.Gson_button);
        textView = (TextView) findViewById(R.id.textView);
        JsonButton = (Button) findViewById(R.id.Json_button);
        JsonButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Jtext();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        GsonButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Gtext();
            }
        });
        try {
            //获得zk_new_json.txt文件输入流,要变编译成String的JSON格式
            InputStream json = getAssets().open("zk_new_json.txt");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte data[] = new byte[1024];
            int lenth = -1;
            while ((lenth = json.read(data)) != -1) {
                out.write(data, 0, lenth);
                out.flush();
            }
            out.close();
            json.close();
            mJSONdata = out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Jtext() throws JSONException {
        String content = "";
        JSONObject jsonObject = new JSONObject(mJSONdata);
        JSONObject data1 = jsonObject.getJSONObject("data");
        JSONArray course = data1.getJSONArray("course");
        for (int i = 0; i  course = date.getData().getCourse();
        for (int i = 0; i < course.size(); i++) {
            List courseDetail = course.get(i).getCourseDetail();

            data += "专业:" + courseDetail.get(0).getProfessional() + "\n";
            data += "大学:" + courseDetail.get(1).getUniversity() + "\n";
            data += "专业介绍:" + courseDetail.get(2).getBrief() + "\n";
            data += "地区:" + courseDetail.get(3).getRegion() + "\n";
            data += "要求:" + courseDetail.get(4).getRequire() + "\n";
            data += "考试周期:" + courseDetail.get(5).getFrequency() + "\n";
            data += "考试科目:" + courseDetail.get(6).getSubject() + "\n";
            List exams = courseDetail.get(7).getExams();
            for (int j = 0; j < exams.size(); j++) {
                List examDetail = exams.get(j).getExamDetail();
                data += "考试年份:" + examDetail.get(0).getExamTimeYear() + "\n";
                data += "考试月份:" + examDetail.get(1).getExamTimeMonth() + "\n";
                data += "登记时间:" + examDetail.get(2).getSignUpTime() + "\n";
                if(examDetail.get(4).getExamScore().equals("null")){
                    data += "公布成绩:待公布 \n";
                }else{
                    data += "公布成绩:" + examDetail.get(4).getExamScore() + "\n";
                }
                List examDay = examDetail.get(3).getExamDay();
                for (int k = 0; k < examDay.size(); k++) {
                    List day = examDay.get(k).getDay();
                    data += "考试日期:" + day.get(0).getTimeDay() + "\n";
                    List timeUp = day.get(1).getTimeUp();
                    List timeDown = day.get(2).getTimeDown();
                    if(timeUp.size() == 1){
                        data += "上午暂无考试安排";
                    }
                    if (timeUp.size() == 2) {
                        data += "考试时间:" + timeUp.get(0) + "\n考试科目:" + timeUp.get(1);
                    }
                    if (timeDown.size() == 2) {
                        data += "考试时间:" + timeDown.get(0) + "\n考试科目:" + timeDown.get(1);
                    }
                    if(timeDown.size() == 1){
                        data += "下午暂无考试安排";
                    }
                    if(timeDown.size() == 3){
                        data += "考试时间:"+timeDown.get(0)+
                                "\n考试科目1:"+timeDown.get(1)+
                                "\n考试科目2:"+timeDown.get(2);
                    }
                }

            }


        }
        textView.setText("Gson解析:\n"+data);
    }
}

你可能感兴趣的:(Gson解析/JSON解析/新建)