Android Json解析

JSON(JavaScript Object Notation)是一种轻量级数据交换格式基本结构有对象(JsonObject)、数组(JsonArray)。
Gson是谷歌提供的一个面向对象用来可以快速高效在Java对象和JSON数据之间进行映射的java类库。可以将一个JSON字符串转成一个Java对象,也可以将一个Java对象转换成一个JSON字符串。
Fast-json是阿里巴巴工程师开发的一个性能很好的Java语言实现JSON解析器和生成器,性能极好,据说能超越其他任何的Java JSON解析器。特点是快,功能强大,支持jdk类的任意Javabean类,collection,map,date或enum。无依赖,支持注解和全类型序列化。
JSON简单语法:
{} 双括号表示对象
eg:{“name”: “Xiaoming”} 可以理解为是一个包含name为Xiaoming的对象
[] 中括号表示数组
eg:[{“course”: “Math”},{“course”: “IT”}]就表示包含两个对象的数组
“”双引号内是属性或值
传统的JSON解析
1、生成JSOn字符串

import org.json.JSONException;
import org.json.JSONObject;
public class JsonUtils {
    static JSONObject jsonObject = new JSONObject();//生成json对象
    public static JSONObject addJsonObject(String key, Object value){
         try {
                jsonObject.append(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }//通过键值对存放json数据
         return jsonObject;
    }
    public static String createJsonString() {
        return jsonObject.toString();//返回json格式字符串
    }
}

---------------------------------------------------------------
public class Main {
    public static void main(String[] args) {
        JsonUtils.addJsonObject("name", "xiaohua");
        JsonUtils.addJsonObject("name", "xiaoming");
        JsonUtils.addJsonObject("name", "xiaojuan");
        JsonUtils.addJsonObject("age", "20");
        String jsonString=JsonUtils.createJsonString();
        System.out.println("jsonString:"+jsonString);
    }   
}
输出:
--------------------------------------------------------------
jsonString:{"age":["20"],"name":["xiaohua","xiaoming","xiaojuan"]}

2.解析JSON字符串

分为以下三种数据类型,JavaBean,List数组,嵌套Map的List数组:


public class Person {
private int id;
private String name;
private String address;
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 getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}


}
------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;


/** * 完成对json数据的解析 * */
public class JsonUtils {


    public static Person getPerson(String jsonString) {
        Person person = new Person();
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject personObject = jsonObject.getJSONObject("person");
            person.setId(personObject.getInt("id"));
            person.setName(personObject.getString("name"));
            person.setAddress(personObject.getString("address"));
        } catch (Exception e) {
            // TODO: handle exception
        }
        return person;
    }

    public static List<Person> getPersons(String key, String jsonString) {
        List<Person> list = new ArrayList<Person>();
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            // 返回json的数组
            JSONArray jsonArray = jsonObject.getJSONArray(key);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                Person person = new Person();
                person.setId(jsonObject2.getInt("id"));
                person.setName(jsonObject2.getString("name"));
                person.setAddress(jsonObject2.getString("address"));
                list.add(person);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }

    public static List<String> getList(String key, String jsonString) {
        List<String> list = new ArrayList<String>();
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray(key);
            for (int i = 0; i < jsonArray.length(); i++) {
                String msg = jsonArray.getString(i);
                list.add(msg);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }   
}
----------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        String jsonString ="{\"person\":{\"id\":\"20\",\"name\":\"xiaohua\",\"address\":\"shenzhen\"}}";
        person = JsonUtils.getPerson(jsonString);
        System.out.println("id:"+person.getId());
        System.out.println("name:"+person.getName());
        System.out.println("address:"+person.getAddress());
        String jsonString1="{\"person\":[{\"id\":\"20\",\"name\":\"xiaohua\",\"address\":\"shenzhen\"},{\"id\":\"21\",\"name\":\"xiaoming\",\"address\":\"shanghai\"},{\"id\":\"22\",\"name\":\"xiaojuan\",\"address\":\"suzhou\"}]}";
        List<Person> list = new ArrayList<Person>();
        list=JsonUtils.getPersons("person", jsonString1);
        for(int i=0;i<list.size();i++){
            person=list.get(i);
            System.out.println("id:"+person.getId());
            System.out.println("name:"+person.getName());
            System.out.println("address:"+person.getAddress());

        }
    }   
}
输出:
-------------------------------------------------------------
id:20
name:xiaohua
address:shenzhen
id:20
name:xiaohua
address:shenzhen
id:21
name:xiaoming
address:shanghai
id:22
name:xiaojuan
address:suzhou

使用GSON解析
Gson的基本用法:定义实体类,根据需要可以将json生成单个实体或列表实体集合。
1.生成json字符串

import com.google.gson.Gson;

public class JsonUtils {

    public static String createJsonObject(Object obj) {
        Gson gson = new Gson();
        String str = gson.toJson(obj);
        return str;

    }
}
----------------------------------------------------------------
public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setAddress("shenzhen");
        person.setId(20);
        person.setName("xiaohua");
        String jsonresult=JsonUtils.createJsonObject(person);
        System.out.println(jsonresult);
    }   
}
输出结果:
---------------------------------------------------------------
{"id":20,"name":"xiaohua","address":"shenzhen"}

2.解析JSON


public class Person {
    Person(){

    }
private int id;
private String name;
private String address;
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 getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}


}
-------------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;

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

import com.google.gson.Gson;

public class JsonUtils {

    public static  <T> T getPerson(String jsonString, Class cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = (T) gson.fromJson(jsonString, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }

    /** * 使用Gson进行解析 List */
    public static  <T>List<T> getPersons(String key, String jsonString, Class cls) {
        List<T> list = new ArrayList<T>();
        T t = null;
        try {
            Gson gson = new Gson();
              JSONObject jsonObject = new JSONObject(jsonString);
                // 返回json的数组
                JSONArray jsonArray = jsonObject.getJSONArray(key);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                    t = (T) gson.fromJson(jsonObject2.toString(), cls);
                    list.add(t);
                }
        } catch (Exception e) {
        }
        return list;
    }


}

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

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;


public class Main {
    public static void main(String[] args) {
        Gson gson =new Gson();
        Person person = new Person();
        String jsonString ="{\"id\":\"20\",\"name\":\"xiaohua\",\"address\":\"shenzhen\"}";
        person=gson.fromJson(jsonString, Person.class);
        System.out.println("id:"+person.getId());
        System.out.println("name:"+person.getName());
        System.out.println("address:"+person.getAddress());
        String jsonString1="{\"person\":[{\"id\":\"20\",\"name\":\"xiaohua\",\"address\":\"shenzhen\"},{\"id\":\"21\",\"name\":\"xiaoming\",\"address\":\"shanghai\"},{\"id\":\"22\",\"name\":\"xiaojuan\",\"address\":\"suzhou\"}]}";
        List<Person> list = new ArrayList<Person>();
        list=JsonUtils.getPersons("person", jsonString1, Person.class);
        for(int i=0;i<list.size();i++){
            person=list.get(i);
            System.out.println("id:"+person.getId());
            System.out.println("name:"+person.getName());
            System.out.println("address:"+person.getAddress());

        }
    }   
}
输出结果:
---------------------------------------------------------------
id:20
name:xiaohua
address:shenzhen
id:20
name:xiaohua
address:shenzhen
id:21
name:xiaoming
address:shanghai
id:22
name:xiaojuan
address:suzhou

使用FastJSon解析


public class Person {
    Person(){

    }
private int id;
private String name;
private String address;
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 getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}


}
-----------------------------------------------------------
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

public class JsonUtils {

    public static  <T>T getPerson(String jsonstring, Class cls) {
        T t = null;
        try {
            t = (T) JSON.parseObject(jsonstring, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return t;
    }

    public static  List getPersons(String jsonstring, Class cls) {
        List list = new ArrayList();
        try {
            list = JSON.parseArray(jsonstring, cls);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return list;
    }

}
-----------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;


public class Main {
    public static void main(String[] args) {
        Gson gson =new Gson();
        Person person = new Person();
        String jsonString ="{\"id\":\"20\",\"name\":\"xiaohua\",\"address\":\"shenzhen\"}";
        person=gson.fromJson(jsonString, Person.class);
        System.out.println("id:"+person.getId());
        System.out.println("name:"+person.getName());
        System.out.println("address:"+person.getAddress());
        String jsonString1="[{\"id\":\"20\",\"name\":\"xiaohua\",\"address\":\"shenzhen\"},{\"id\":\"21\",\"name\":\"xiaoming\",\"address\":\"shanghai\"},{\"id\":\"22\",\"name\":\"xiaojuan\",\"address\":\"suzhou\"}]";
        List<Person> list = new ArrayList<Person>();
        list=JsonUtils.getPersons( jsonString1, Person.class);
        for(int i=0;i<list.size();i++){
            person=list.get(i);
            System.out.println("id:"+person.getId());
            System.out.println("name:"+person.getName());
            System.out.println("address:"+person.getAddress());

        }
    }   
}

JSON格式数据相对于XML格式的数据传输会更节省流量,传输效率更高。在这三种解析方式中FastJson是效率最高的,推荐使用。

你可能感兴趣的:(java,android,json,gson,fastjson)