最简单简洁高效的Json数据解析

Posted mfmdaoyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最简单简洁高效的Json数据解析相关的知识,希望对你有一定的参考价值。

一.无图无真相
技术分享
技术分享
二.主要代码
1.导入jar包

拷贝fastjson.jar包到projectlibs包下

2.封装工具类JsonUtil.java

package com.example.parsejsondemo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * Json解析的工具类
 * 
 * @author 孤狼
 * @since 2015-8-8
 */

public class JsonUtil {

    /**
     * 将JSON转成 数组类型对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> getListFromString(String json, Class<T> clazz) {
        List<T> t = null;
        try {
            t = JSON.parseArray(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 将list转换成String
     *
     * @param list
     *            准备转换的集合
     * @return string
     * @throws Exception
     */
    public static String getStringFromList(List list) {
        String string = "";
        try {
            string = JSON.toJSONString(list, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return string;
    }

    /**
     * 将java对象转换成json字符串
     *
     * @param obj
     *            准备转换的对象
     * @return json字符串
     * @throws Exception
     */
    public static String getStringFromObject(Object obj) {
        String json = "";
        try {
            json = JSON.toJSONString(obj, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 将json字符串转换成java对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return object
     */
    public static <T> T getObjectFromString(String json, Class<T> clazz) {
        T t = null;
        try {
            t = JSON.parseObject(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 将 json 字符串转为 JSONArray 对象;
     *
     * @param json
     * @return JsonArray
     */
    public static JSONArray getJsonArray(String json) {
        JSONArray array = null;
        try {
            array = JSON.parseArray(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return array;
    }

    /**
     * 将 json 字符串转为 JSONObect 对象
     *
     * @param json
     * @return JSONObject
     */
    public static JSONObject getJsonObject(String json) {
        JSONObject object = null;
        try {
            object = (JSONObject) JSON.parse(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
}

3.封装数据实体类(实例:ArticleBean.java和ArticleDetailBean.java)

package com.example.parsejsondemo;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章实体类
 * 
 * @author 孤狼
 * @since 2015-8-8
 */
public class ArticleBean {

    private String title = "";
    private String title_image_url = "";
    private String create_time = "";
    private long article_id = 0;
    // 查看用户的信息
    private List<UserInfoBean> headimages = new ArrayList<UserInfoBean>();

    public String getTitle() {
        return title;
    }

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

    public String getTitle_image_url() {
        return title_image_url;
    }

    public void setTitle_image_url(String title_image_url) {
        this.title_image_url = title_image_url;
    }

    public String getCreate_time() {
        return create_time;
    }

    public void setCreate_time(String create_time) {
        this.create_time = create_time;
    }

    public List<UserInfoBean> getHeadimages() {
        return headimages;
    }

    public void setHeadimages(List<UserInfoBean> headimages) {
        this.headimages = headimages;
    }

    public long getArticle_id() {
        return article_id;
    }

    public void setArticle_id(long article_id) {
        this.article_id = article_id;
    }
}
package com.example.parsejsondemo;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章详情
 * 
 * @author 孤狼
 * @since 2015-8-8
 */
public class ArticleDetailBean {

    private String content;
    // 图片集合类
    private List<ImageResult> images = new ArrayList<ImageResult>();
    private String create_time;
    // 点赞状态
    private boolean if_dianzan;
    // 评论数
    private int comment_num;
    // 第几期 例:第5期
    private String times;
    private String title;
    private long article_id;
    private int dianzan_num;

    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 getCreate_time() {
        return create_time;
    }

    public void setCreate_time(String create_time) {
        this.create_time = create_time;
    }

    public boolean isIf_dianzan() {
        return if_dianzan;
    }

    public void setIf_dianzan(boolean if_dianzan) {
        this.if_dianzan = if_dianzan;
    }

    public int getComment_num() {
        return comment_num;
    }

    public void setComment_num(int comment_num) {
        this.comment_num = comment_num;
    }

    public String getTimes() {
        return times;
    }

    public void setTimes(String times) {
        this.times = times;
    }

    public long getArticle_id() {
        return article_id;
    }

    public void setArticle_id(long article_id) {
        this.article_id = article_id;
    }

    public int getDianzan_num() {
        return dianzan_num;
    }

    public void setDianzan_num(int dianzan_num) {
        this.dianzan_num = dianzan_num;
    }

    public List<ImageResult> getImages() {
        return images;
    }

    public void setImages(List<ImageResult> images) {
        this.images = images;
    }

    @Override
    public String toString() {
        return "ArticleDetailResult [title=" + title + ", content=" + content
                + ", create_time=" + create_time + ", comment_num="
                + comment_num + ", times=" + times + ", article_id="
                + article_id + ", dianzan_num=" + dianzan_num + "]";
    }

}

4.代码中调用
a.解析 JsonList类型

package com.example.parsejsondemo;

import java.util.List;

import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 解析 JsonList类型
 *
 * @author 孤狼
 * @since 2015-8-8
 * */
public class JsonListActivity extends Activity {
    private String data = "[ { \"article_id\": 682, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"给你的一封情书\", \"title_image_url\": \"http://e.hiphotos.baidu.com/image/w%3D310/sign=d0aa9ba85eb5c9ea62f305e2e538b622/b90e7bec54e736d1cb1f21ab9e504fc2d5626901.jpg\" }, { \"article_id\": 681, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"女人,你的别名是愚蠢\", \"title_image_url\": \"http://f.hiphotos.baidu.com/image/w%3D310/sign=ef8e5a82778b4710ce2ffbcdf3cfc3b2/72f082025aafa40f1ed46c7eae64034f78f01906.jpg\" }, { \"article_id\": 680, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"明确\", \"title_image_url\": \"http://g.hiphotos.baidu.com/image/w%3D310/sign=5c6d742fe4fe9925cb0c6f5104a95ee4/3ac79f3df8dcd100dce594cb768b4710b8122fda.jpg\" }, { \"article_id\": 679, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"秋之随想\", \"title_image_url\": \"http://d.hiphotos.baidu.com/image/w%3D310/sign=f9fd8128e9c4b7453494b117fffd1e78/0bd162d9f2d3572ce2779bdd8813632762d0c31e.jpg\" }, { \"article_id\": 681, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"女人,你的别名是愚蠢\", \"title_image_url\": \"http://f.hiphotos.baidu.com/image/w%3D310/sign=ef8e5a82778b4710ce2ffbcdf3cfc3b2/72f082025aafa40f1ed46c7eae64034f78f01906.jpg\" }, { \"article_id\": 680, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"明确\", \"title_image_url\": \"http://g.hiphotos.baidu.com/image/w%3D310/sign=5c6d742fe4fe9925cb0c6f5104a95ee4/3ac79f3df8dcd100dce594cb768b4710b8122fda.jpg\" }, { \"article_id\": 679, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"秋之随想\", \"title_image_url\": \"http://d.hiphotos.baidu.com/image/w%3D310/sign=f9fd8128e9c4b7453494b117fffd1e78/0bd162d9f2d3572ce2779bdd8813632762d0c31e.jpg\" }, { \"article_id\": 681, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"女人,你的别名是愚蠢\", \"title_image_url\": \"http://f.hiphotos.baidu.com/image/w%3D310/sign=ef8e5a82778b4710ce2ffbcdf3cfc3b2/72f082025aafa40f1ed46c7eae64034f78f01906.jpg\" }, { \"article_id\": 680, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"明确\", \"title_image_url\": \"http://g.hiphotos.baidu.com/image/w%3D310/sign=5c6d742fe4fe9925cb0c6f5104a95ee4/3ac79f3df8dcd100dce594cb768b4710b8122fda.jpg\" }, { \"article_id\": 679, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"秋之随想\", \"title_image_url\": \"http://d.hiphotos.baidu.com/image/w%3D310/sign=f9fd8128e9c4b7453494b117fffd1e78/0bd162d9f2d3572ce2779bdd8813632762d0c31e.jpg\" }, { \"article_id\": 681, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"女人。你的别名是愚蠢\", \"title_image_url\": \"http://f.hiphotos.baidu.com/image/w%3D310/sign=ef8e5a82778b4710ce2ffbcdf3cfc3b2/72f082025aafa40f1ed46c7eae64034f78f01906.jpg\" }, { \"article_id\": 680, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"明确\", \"title_image_url\": \"http://g.hiphotos.baidu.com/image/w%3D310/sign=5c6d742fe4fe9925cb0c6f5104a95ee4/3ac79f3df8dcd100dce594cb768b4710b8122fda.jpg\" }, { \"article_id\": 679, \"create_time\": \"12:13\", \"headimages\": [], \"title\": \"秋之随想\", \"title_image_url\": \"http://d.hiphotos.baidu.com/image/w%3D310/sign=f9fd8128e9c4b7453494b117fffd1e78/0bd162d9f2d3572ce2779bdd8813632762d0c31e.jpg\" } ]";
    private List<ArticleBean> list;
    private ListView listView;
    private ImageLoader instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = ImageLoader.getInstance();
        listView = (ListView) findViewById(R.id.listView);
        // 把String类型的json解析成List集合
        list = JsonUtil.getListFromString(data, ArticleBean.class);
        // 设置适配器
        listView.setAdapter(new CustomAdapter());
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                startActivity(new Intent(JsonListActivity.this,
                        JsonObjectActivity.class));
            }
        });
    }

    // 定义适配器
    class CustomAdapter extends BaseAdapter {

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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // 查找控件
            ViewHold hold;
            if (convertView != null) {
                hold = (ViewHold) convertView.getTag();
            } else {
                hold = new ViewHold();
                convertView = View.inflate(getApplicationContext(),
                        R.layout.list_item, null);
                hold.iv_cover = (ImageView) convertView
                        .findViewById(R.id.iv_coner);
                hold.tv_time = (TextView) convertView
                        .findViewById(R.id.tv_time);
                hold.tv_title = (TextView) convertView
                        .findViewById(R.id.tv_title);
                convertView.setTag(hold);
            }
            // 填充数据
            hold.tv_time.setText("孤狼   公布时间:"
                    + list.get(position).getCreate_time());
            hold.tv_title.setText(list.get(position).getTitle());
            instance.displayImage(list.get(position).getTitle_image_url(),
                    hold.iv_cover);
            return convertView;
        }

        class ViewHold {
            private ImageView iv_cover;
            private TextView tv_title;
            private TextView tv_time;
        }
    }
}

b.解析 JsonObject类型

package com.example.parsejsondemo;

import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 解析 JsonObject类型
 *
 * @author 孤狼
 * @since 2015-8-8
 * */
public class JsonObjectActivity extends Activity {
    // json数据
    private String data = "{ \"article_id\": 682, \"comment_num\": 26, \"content\": \"你是清晨,\\r\\n是我醒来后的第一缕,\\r\\n是我起床后的第一缕清风。\\r\\n是我看见的第一抹浓绿色。\\r\\n你是的阳光温暖我的。\\r\\n你是中午,\\r\\n是手中香甜的饭菜。\\r\\n是我午睡时躺着的枕头。

\\r\\n你是晚上,\\r\\n是黑中的一屡凉爽,\\r\\n是黑暗中的平静心态,\\r\\n是惊恐中的心灵安慰。\\r\\n是天空中的闪烁繁星,\\r\\n你是我最遥远的。\\r\\n我的恋人。

\\r\\n\", \"create_time\": \"06-12 12:13\", \"dianzan_num\": 411, \"if_dianzan\": true, \"images\": [ { \"image_id\": 3595, \"image_url\": \"http://e.hiphotos.baidu.com/image/w%3D310/sign=d0aa9ba85eb5c9ea62f305e2e538b622/b90e7bec54e736d1cb1f21ab9e504fc2d5626901.jpg\" }, { \"image_id\": 3596, \"image_url\": \"http://7xjora.com2.z0.glb.qiniucdn.com/644121332662Etjmn.jpg?imageView2/0/w/500/h/500\" }, { \"image_id\": 3597, \"image_url\": \"http://7xjora.com2.z0.glb.qiniucdn.com/1650121333675aY09a.jpg?imageView2/0/w/500/h/500\" }, { \"image_id\": 3598, \"image_url\": \"http://7xjora.com2.z0.glb.qiniucdn.com/120712133440245oBv.jpg?imageView2/0/w/500/h/500\" }, { \"image_id\": 3599, \"image_url\": \"http://7xjora.com2.z0.glb.qiniucdn.com/940121334941gy1Ii.jpg?

imageView2/0/w/500/h/500\" } ], \"times\": \"第682期\", \"title\": \"给你的一封情书\" }"; private ImageLoader instance; private TextView tv_title; private TextView tv_time; private ImageView iv_cover; private ArticleDetailBean detailBean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_object); instance = ImageLoader.getInstance(); iv_cover = (ImageView) findViewById(R.id.iv_coner); tv_time = (TextView) findViewById(R.id.tv_time); tv_title = (TextView) findViewById(R.id.tv_title); // 把json数据解析成Object类型实体类 detailBean = JsonUtil .getObjectFromString(data, ArticleDetailBean.class); // 填充数据 tv_title.setText(detailBean.getTitle()); tv_time.setText(detailBean.getContent()); instance.displayImage(detailBean.getImages().get(0).getImage_url(), iv_cover); } }

三.说明

Json数据是client和服务端交互的主要形式之中的一个,解析Json的方法工具也非常多,比方goole的Gson(能够去看前面关于Gson解析数据的方法)等等,而fastjson.jar解析json数据感觉非常强大高效和简洁。有用非常easy:引入jar包—>封装工具类—–>封装要解析的数据对象—>调用工具解析。代码非常easy。如有疑问请留言—-孤狼

四.实例Demo

最简单高效简洁好用的Json解析






以上是关于最简单简洁高效的Json数据解析的主要内容,如果未能解决你的问题,请参考以下文章

ios中json解析出现的null问题

基于开源库jsoncpp的json字符串解析

ios中json解析出现的null问题

求关于java中无key的json 解析

函数式编程:高效简洁地对数据查询与变换

Retrofit原理解析最简洁的思路