利用Gson解析json数据

在这里绕了好久,做完才发现,原来“一行”代码就解决了,难点主要就是把需要解析的json数据构建成bean类,话不多说,开始干

json数据:https://www.sojson.com/open/api/lunar/json.shtml

{
  "status": 200,
  "message": "success",
  "data": {
    "year": 2018,
    "month": 4,
    "day": 24,
    "lunarYear": 2018,
    "lunarMonth": 3,
    "lunarDay": 9,
    "cnyear": "贰零壹捌 ",
    "cnmonth": "三",
    "cnday": "初九",
    "hyear": "戊戌",
    "cyclicalYear": "戊戌",
    "cyclicalMonth": "丙辰",
    "cyclicalDay": "丙戌",
    "suit": "祭祀,沐浴,破屋,坏垣,求医,治病,解除,馀事勿取",
    "taboo": "嫁娶,开市,交易,入宅,安葬",
    "animal": "狗",
    "week": "Tuesday",
    "festivalList": [],
    "jieqi": {
      "5": "清明",
      "20": "谷雨"
    },
    "maxDayInMonth": 29,
    "leap": false,
    "lunarYearString": "戊戌",
    "bigMonth": false
  }
}

这就是我要解析的Json数据内容

第一步:首先添加Gson依赖

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'

第二步:构建Bean对象

public class NewStatus {
    private int status;
    private String message;
    private News data;

    public News getData() {
        return data;
    }

    public void setData(News data) {
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    @Override
    public String toString() {
        return "NewStatus[status=" + status+",message=" + message
                + ",data=" + data+"]";
    }
}

这里NewStatus其实就是数据头

然后把data里面的数据分别写出来,这里要注意的是,构建的Bean类的值要跟Json里面的Key值要完全一样!!不然无法解析

这里最重要的一步其实就是构建json数据的实体类,只要这个弄清楚了,剩下的就好说了

NewStatus newStatus =new  Gson().fromJson(response,NewStatus.class);

这一步就是Gson解析的关键代码,其实就只有这一行而已~

-------------------------------------------------手动分割线--------------------------------------------------------------------

就这么一个Gson解析json数据,搞了几天,自学果然是难哎。。。

之前主要难点就是因为不知道如何从服务器上获取Json数据,在这里绕了好久,后来终于弄清楚了,感谢网上的前辈总结的经验!

如何从服务器获取json数据源?

我这里用到了HttpClient方法,不过HttpClient在android4.0以后就不好用了,直接用会出现报错~不过没关系,只要添加如下代码即可

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

直接上HttpClient获取Json数据的方法

public static String netLink(String url) {
    HttpClient httpClient = new DefaultHttpClient();
    //访问指定的服务器
    HttpGet httpGet = new HttpGet(url);
    HttpResponse httpResponse = null;
    response = null;
    try {
        httpResponse = httpClient.execute(httpGet);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        //200说明请求和响应都是成功的
        HttpEntity entity = httpResponse.getEntity();
        try {
            response = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return response;
}

这里的response就是从服务器获取的Json数据!

最后贴完整代码MainActivity .java

public class MainActivity extends AppCompatActivity {

    private static String response;
    private Button bt;
    private TextView tv;
    private Gson gson;
    private String url;
    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue = Volley.newRequestQueue(this);

        url ="https://www.sojson.com/open/api/lunar/json.shtml";

        bt = (Button) findViewById(R.id.gon_bt);
        tv = (TextView) findViewById(R.id.gon_tv);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                netLink(url);
                NewStatus newStatus =new  Gson().fromJson(response,NewStatus.class);
                tv.setText(newStatus.getData().toString());

            }
        });
    }





    public static String netLink(String url) {
        HttpClient httpClient = new DefaultHttpClient();
        //访问指定的服务器
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = null;
        response = null;
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            //200说明请求和响应都是成功的
            HttpEntity entity = httpResponse.getEntity();
            try {
                response = EntityUtils.toString(entity, "utf-8");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return response;
    }
}

实体类NewStatus.java

public class NewStatus {
    private int status;
    private String message;
    private News data;

    public News getData() {
        return data;
    }

    public void setData(News data) {
        this.data = data;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    @Override
    public String toString() {
        return "NewStatus[status=" + status+",message=" + message
                + ",data=" + data+"]";
    }
}

News.java

public class News {
    private int year;
    private int day;
    private int lunarYear;
    private int lunarMonth;
    private int lunarDay;
    private String cnyear;
    private String cnmonth;
    private String cnday;
    private String hyear;
    private String cyclicalYear;
    private String cyclicalMonth;
    private String cyclicalDay;
    private String suit;
    private String taboo;
    private String animal;
    private String week;
    private int maxDayInMonth;
    private String lunarYearString;

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }


    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getLunarYear() {
        return lunarYear;
    }

    public void setLunarYear(int lunarYear) {
        this.lunarYear = lunarYear;
    }

    public int getLunarMonth() {
        return lunarMonth;
    }

    public void setLunarMonth(int lunarMonth) {
        this.lunarMonth = lunarMonth;
    }

    public int getLunarDay() {
        return lunarDay;
    }

    public void setLunarDay(int lunarDay) {
        this.lunarDay = lunarDay;
    }

    public String getCnyear() {
        return cnyear;
    }

    public void setCnyear(String cnyear) {
        this.cnyear = cnyear;
    }

    public String getCnmonth() {
        return cnmonth;
    }

    public void setCnmonth(String cnmonth) {
        this.cnmonth = cnmonth;
    }

    public String getCnday() {
        return cnday;
    }

    public void setCnday(String cnday) {
        this.cnday = cnday;
    }

    public String getHyear() {
        return hyear;
    }

    public void setHyear(String hyear) {
        this.hyear = hyear;
    }

    public String getCyclicalYear() {
        return cyclicalYear;
    }

    public void setCyclicalYear(String cyclicalYear) {
        this.cyclicalYear = cyclicalYear;
    }

    public String getCyclicalMonth() {
        return cyclicalMonth;
    }

    public void setCyclicalMonth(String cyclicalMonth) {
        this.cyclicalMonth = cyclicalMonth;
    }

    public String getCyclicalDay() {
        return cyclicalDay;
    }

    public void setCyclicalDay(String cyclicalDay) {
        this.cyclicalDay = cyclicalDay;
    }

    public String getSuit() {
        return suit;
    }

    public void setSuit(String suit) {
        this.suit = suit;
    }

    public String getTaboo() {
        return taboo;
    }

    public void setTaboo(String taboo) {
        this.taboo = taboo;
    }

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public String getWeek() {
        return week;
    }

    public void setWeek(String week) {
        this.week = week;
    }

    public int getMaxDayInMonth() {
        return maxDayInMonth;
    }

    public void setMaxDayInMonth(int maxDayInMonth) {
        this.maxDayInMonth = maxDayInMonth;
    }

    public String getLunarYearString() {
        return lunarYearString;
    }

    public void setLunarYearString(String lunarYearString) {
        this.lunarYearString = lunarYearString;
    }

    @Override
    public String toString() {
        return "News[year="+ year +",day=" + day + ",lunarYear=" + lunarYear+
                ",lunarMonth=" + lunarMonth + ",cyclicalDay=" + cyclicalDay + ",suit= "+ suit+
                ",taboo="+ taboo+",animal=" + animal+ ",week=" + week +",maxDayInMonth=" + maxDayInMonth
                +",lunarYearString=" + lunarYearString +"]";
    }
}

到这里就结束啦,这里面需要注意的就是添加两个依赖,一个是Gson的,另一个就是HttpClient的依赖

useLibrary 'org.apache.http.legacy'

compile "org.apache.httpcomponents:httpcore:4.3.2"

Demo点这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值