zoukankan      html  css  js  c++  java
  • Java-JSON

     

     1         <!-- fastjson -->
     2         <dependency>
     3             <groupId>com.alibaba</groupId>
     4             <artifactId>fastjson</artifactId>
     5             <version>1.2.47</version>
     6         </dependency>
     7 
     8         <!-- gson -->
     9         <dependency>
    10             <groupId>com.google.code.gson</groupId>
    11             <artifactId>gson</artifactId>
    12             <version>2.8.2</version>
    13         </dependency>

    fastJson

      1 import static com.alibaba.fastjson.util.TypeUtils.castToBoolean;
      2 
      3 import java.io.Serializable;
      4 import java.lang.reflect.Type;
      5 import java.util.ArrayList;
      6 import java.util.Collection;
      7 import java.util.Iterator;
      8 import java.util.List;
      9 import java.util.ListIterator;
     10 import java.util.RandomAccess;
     11 
     12 import com.alibaba.fastjson.JSON;
     13 import com.alibaba.fastjson.JSONObject;
     14 import com.alibaba.fastjson.parser.ParserConfig;
     15 import com.alibaba.fastjson.util.TypeUtils;
     16 
     17 /**
     18  * JSONArray源码
     19  */
     20 public class JSONArray1 extends JSON implements List<Object>, Cloneable, RandomAccess, Serializable {
     21 
     22     private final List<Object> list;
     23     protected transient Object relatedArray;
     24     protected transient Type   componentType;
     25     //使用无参构造创建JSONArray的时候,初始化一个空arrayList
     26     public JSONArray1(){
     27         this.list = new ArrayList<Object>();
     28     }
     29     //使用有参构造,将参数list赋值给JSONArray的属性list
     30     public JSONArray1(List<Object> list){
     31         this.list = list;
     32     }
     33     //使用无参构造,创建指定参数大小的list
     34     public JSONArray1(int initialCapacity){
     35         this.list = new ArrayList<Object>(initialCapacity);
     36     }
     37 
     38     //set和get方法
     39     public Object getRelatedArray() {return relatedArray;}
     40     public void setRelatedArray(Object relatedArray){this.relatedArray = relatedArray;}
     41     public Type getComponentType() {return componentType;}
     42     public void setComponentType(Type componentType){this.componentType = componentType;}
     43 
     44     //获取存储数据的list的大小
     45     public int size() {
     46         return list.size();
     47     }
     48     //判断存储数据的list是否为空
     49     public boolean isEmpty() {
     50         return list.isEmpty();
     51     }
     52     //判断存储数据的list是否包含某个对象
     53     public boolean contains(Object o) {
     54         return list.contains(o);
     55     }
     56     //获取存储数据的list的迭代器对象
     57     public Iterator<Object> iterator() {
     58         return list.iterator();
     59     }
     60     //将存储数据的list转成数组
     61     public Object[] toArray() {
     62         return list.toArray();
     63     }
     64     //将参数中的数据,添加list中,并将list转成参数中数组的类型的数组返回
     65     public <T> T[] toArray(T[] a) {
     66         return list.toArray(a);
     67     }
     68     //向存储数据的list中添加元素,添加成功返回true
     69     public boolean add(Object e) {
     70         return list.add(e);
     71     }
     72     //向存储数据的list中添加元素,返回该JSONArray对象
     73     public JSONArray1 fluentAdd(Object e) {
     74         list.add(e);
     75         return this;
     76     }
     77     //从存储数据的list中移除指定元素,移除成功返回true
     78     public boolean remove(Object o) {
     79         return list.remove(o);
     80     }
     81     //从存储数据的list中移除指定元素,返回该JSONArray对象
     82     public JSONArray1 fluentRemove(Object o) {
     83         list.remove(o);
     84         return this;
     85     }
     86     //判断list中是否包含指定集合中的所有元素
     87     public boolean containsAll(Collection<?> c) {
     88         return list.containsAll(c);
     89     }
     90     //添加指定集合中的所有元素到list中,添加成功返回true
     91     public boolean addAll(Collection<? extends Object> c) {
     92         return list.addAll(c);
     93     }
     94     //添加指定集合中的所有元素到list中,返回该JSONArray对象
     95     public JSONArray1 fluentAddAll(Collection<? extends Object> c) {
     96         list.addAll(c);
     97         return this;
     98     }
     99     //添加指定集合中的所有元素到list中指定下标处,添加成功返回true
    100     public boolean addAll(int index, Collection<? extends Object> c) {
    101         return list.addAll(index, c);
    102     }
    103     //添加指定集合中的所有元素到list中指定下标处,返回该JSONArray对象
    104     public JSONArray1 fluentAddAll(int index, Collection<? extends Object> c) {
    105         list.addAll(index, c);
    106         return this;
    107     }
    108     //从list中删除指定集合中的所有元素,删除成功返回true
    109     public boolean removeAll(Collection<?> c) {
    110         return list.removeAll(c);
    111     }
    112     //从list中删除指定集合中的所有元素,返回该JSONArray对象
    113     public JSONArray1 fluentRemoveAll(Collection<?> c) {
    114         list.removeAll(c);
    115         return this;
    116     }
    117     
    118     public boolean retainAll(Collection<?> c) {
    119         return list.retainAll(c);
    120     }
    121 
    122     public JSONArray1 fluentRetainAll(Collection<?> c) {
    123         list.retainAll(c);
    124         return this;
    125     }
    126     //清空list集合
    127     public void clear() {
    128         list.clear();
    129     }
    130     //清空list并返回JSONArray对象
    131     public JSONArray1 fluentClear() {
    132         list.clear();
    133         return this;
    134     }
    135     //添加元素到List的指定下标处
    136     public Object set(int index, Object element) {
    137         if (index == -1) {
    138             list.add(element);
    139             return null;
    140         }
    141         
    142         if (list.size() <= index) {
    143             for (int i = list.size(); i < index; ++i) {
    144                 list.add(null);
    145             }
    146             list.add(element);
    147             return null;
    148         }
    149         
    150         return list.set(index, element);
    151     }
    152     //添加元素到指定下标处,返回JSONArray对象
    153     public JSONArray1 fluentSet(int index, Object element) {
    154         set(index, element);
    155         return this;
    156     }
    157     //添加元素到指定下标
    158     public void add(int index, Object element) {
    159         list.add(index, element);
    160     }
    161     //添加元素到指定下标处,返回JSONArray对象
    162     public JSONArray1 fluentAdd(int index, Object element) {
    163         list.add(index, element);
    164         return this;
    165     }
    166     //删除并返回指定下标处的元素
    167     public Object remove(int index) {
    168         return list.remove(index);
    169     }
    170     //删除指定下标处的元素,返回JSONArray对象
    171     public JSONArray1 fluentRemove(int index) {
    172         list.remove(index);
    173         return this;
    174     }
    175     //获取元素第一次出现的下标
    176     public int indexOf(Object o) {
    177         return list.indexOf(o);
    178     }
    179     //获取元素最后一次出现的下标
    180     public int lastIndexOf(Object o) {
    181         return list.lastIndexOf(o);
    182     }
    183     //获取list特有的迭代器对象
    184     public ListIterator<Object> listIterator() {
    185         return list.listIterator();
    186     }
    187     //根据下标获取list特有的迭代器对象
    188     public ListIterator<Object> listIterator(int index) {
    189         return list.listIterator(index);
    190     }
    191     //截取List
    192     public List<Object> subList(int fromIndex, int toIndex) {
    193         return list.subList(fromIndex, toIndex);
    194     }
    195     //根据下标获取元素
    196     public Object get(int index) {
    197         return list.get(index);
    198     }
    199     //根据下标获取元素,并转成JSONObject对象返回
    200     public JSONObject getJSONObject(int index) {
    201         Object value = list.get(index);
    202 
    203         if (value instanceof JSONObject) {
    204             return (JSONObject) value;
    205         }
    206 
    207         return (JSONObject) toJSON(value);
    208     }
    209     //根据下标获取元素,并转成JSONArray对象返回
    210     public JSONArray1 getJSONArray(int index) {
    211         Object value = list.get(index);
    212 
    213         if (value instanceof JSONArray1) {
    214             return (JSONArray1) value;
    215         }
    216 
    217         return (JSONArray1) toJSON(value);
    218     }
    219     //根据下标获取对象并装成指定的对象类型
    220     public <T> T getObject(int index, Class<T> clazz) {
    221         Object obj = list.get(index);
    222         return TypeUtils.castToJavaBean(obj, clazz);
    223     }
    224     //根据下标获取元素,并转成Boolean
    225     public Boolean getBoolean(int index) {
    226         Object value = get(index);
    227         if (value == null) {
    228             return null;
    229         }
    230         return castToBoolean(value);
    231     }
    232     //根据下标获取元素,并转成Boolean
    233     public boolean getBooleanValue(int index) {
    234         Object value = get(index);
    235         if (value == null) {
    236             return false;
    237         }
    238         return castToBoolean(value).booleanValue();
    239     }
    240     /**
    241      * 根据下标获取对应类型的数据
    242      * getByte、getByteValue、getShort、getShortValue、getInteger、getIntValue
    243      * getLong、getLongValue、getFloat、getFloatValue、getDouble、getDoubleValue
    244      * getBigDecimal、getBigInteger、getString、getDate、getSqlDate、getTimestamp
    245      */
    246     //转成指定类型的ArrayList对象
    247     public <T> List<T> toJavaList(Class<T> clazz) {
    248         List<T> list = new ArrayList<T>(this.size());
    249 
    250         ParserConfig config = ParserConfig.getGlobalInstance();
    251 
    252         for (Object item : this) {
    253             T classItem = (T) TypeUtils.cast(item, clazz, config);
    254             list.add(classItem);
    255         }
    256 
    257         return list;
    258     }
    259     //复制
    260     @Override
    261     public Object clone() {
    262         return new JSONArray1(new ArrayList<Object>(list));
    263     }
    264     public boolean equals(Object obj) {
    265         return this.list.equals(obj);
    266     }
    267     public int hashCode() {
    268         return this.list.hashCode();
    269     }
    270 }
     1 import java.util.HashMap;
     2 import java.util.Map;
     3 import java.util.Map.Entry;
     4 import java.util.Set;
     5 import com.alibaba.fastjson.JSON;
     6 import com.alibaba.fastjson.JSONArray;
     7 import com.alibaba.fastjson.JSONObject;
     8 
     9 /**
    10  * fastjson常用方法介绍
    11  */
    12 public class TestJSON {
    13     public static void main(String[] args) {
    14         //json字符串
    15         String jsonStr = "{'name':'zhangsan','age':'10'}";
    16         String jsonStr2 = "{'name':'zhangsan','age':'11'}";
    17         //将json字符串解析成JSONObject
    18         JSONObject jsonObj = JSON.parseObject(jsonStr);
    19         JSONObject jsonObj2 = JSON.parseObject(jsonStr2);
    20         jsonObj.toJSONString();//转成Json字符串
    21         jsonObj.isEmpty();//判断是否非空
    22         jsonObj.containsKey("name");//是否包含指定key
    23         jsonObj.containsValue("zhangsan");//是否包含指定value
    24         jsonObj.equals(jsonObj2);//判断两个JSONObject是否相等
    25         jsonObj.get("name");//使用map中的取值方法获取value
    26         jsonObj.getString("name");//获取指定key对应的value
    27         jsonObj.size();//获取长度
    28         jsonObj.put("core", "a");//添加元素
    29         jsonObj.remove("name");//删除指定key
    30         jsonObj.clear();//清空
    31         Map<String, Object> map = new HashMap<String, Object>();
    32         jsonObj.putAll(map);//将指定map中的元素添加到JSONObject中
    33         
    34         jsonObj.keySet();//获取所有的key
    35         jsonObj.values();//获取所有的value
    36         
    37         Set<Entry<String, Object>> entrySet = jsonObj.entrySet();//获取所有键值对entry
    38         //遍历
    39         for (Entry<String, Object> entry : entrySet) {
    40             String key = entry.getKey();//获取key
    41             String value = (String) entry.getValue();//获取value
    42             entry.setValue("呵呵");//修改value值
    43         }
    44         
    45         
    46         //json字符串转JSONArray
    47         String str1 = "[{'name':'zhangsan','age':'10'},{'name':'lisi','age':'20'}]";
    48         String str2 = "[{'name':'zhang','age':'15'},{'name':'wangwu','age':'22'}]";
    49         JSONArray jsonArray = JSON.parseArray(str1);
    50         
    51         String jsonString = jsonArray.toJSONString();//转成json字符串
    52         
    53         //遍历这个jsonArray
    54         for (int i = 0; i < jsonArray.size(); i++) {
    55             //获取jsonArray中的每一个元素,元素可以为JSONObject、JSONArray
    56             JSONObject jsonObject = jsonArray.getJSONObject(i);
    57             //然后通过map中的方法entrySet()方法获取键值对
    58             Set<Entry<String, Object>> entrySet2 = jsonObject.entrySet();
    59             for (Entry<String, Object> entry : entrySet2) {
    60                 //然后对entrySet2遍历
    61                 String key = entry.getKey();
    62                 Object value = entry.getValue();
    63             }
    64         }
    65     }
    66 }

    GSON

     1 /**
     2  * 实体类
     3  */
     4 public class Student {
     5     private String name;
     6     private Integer age;
     7     
     8     public Student() {
     9     }
    10     public Student(String name, Integer age) {
    11         super();
    12         this.name = name;
    13         this.age = age;
    14     }
    15     public String getName() {
    16         return name;
    17     }
    18     public void setName(String name) {
    19         this.name = name;
    20     }
    21     public Integer getAge() {
    22         return age;
    23     }
    24     public void setAge(Integer age) {
    25         this.age = age;
    26     }
    27 }
     1 import java.io.FileNotFoundException;
     2 import java.io.FileReader;
     3 import java.util.Iterator;
     4 
     5 import com.google.gson.Gson;
     6 import com.google.gson.JsonArray;
     7 import com.google.gson.JsonElement;
     8 import com.google.gson.JsonIOException;
     9 import com.google.gson.JsonObject;
    10 import com.google.gson.JsonParser;
    11 import com.google.gson.JsonSyntaxException;
    12 /**
    13  * 读取json文件
    14  * JsonObject  就是key和value
    15  * JsonElement  就是一个个value  但是对应的value也有很多可能性,例如可以是一个数组,可以是一个json对象
    16  */
    17 public class JsonAnalysis {
    18     public static void main(String[] args) {
    19         //1.创建一个json解析器
    20         JsonParser parser = new JsonParser();
    21         try {
    22             /**
    23              * JsonParser对象中有三个方法:
    24              *     parse(JsonReader json)
    25              *     parse(Reader json)
    26              *     parse(String json) 将指定的JSON字符串解析为解析树
    27              */
    28                 //2.将流中的json字符串解析并强转成json对象
    29                 JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));
    30                 
    31                 
    32                 /**
    33                  * JsonElement对象提供了对所有类型获取的方法。
    34                  * 
    35                  * 获取值的方法:
    36                  * getAsBigDecimal() 
    37                  * getAsBigInteger() 
    38                  * getAsBoolean()     
    39                  * getAsByte() 
    40                  * getAsCharacter() 
    41                  * getAsDouble() 
    42                  * getAsFloat() 
    43                  * getAsInt() 
    44                  * getAsLong() 
    45                  * getAsNumber() 
    46                  * getAsShort() 
    47                  * getAsString() 
    48                  * 
    49                  * getAsJsonArray() 
    50                  * getAsJsonNull() 
    51                  * getAsJsonObject()     
    52                  * getAsJsonPrimitive() 
    53                  * 
    54                  * 判断的方法:
    55                  * isJsonArray() 是否为一个数组
    56                  * isJsonNull()  
    57                  * isJsonObject() 
    58                  * isJsonPrimitive() 
    59                  * toString() 
    60                  */
    61                 
    62                 //连写
    63                 String name = object.get("name").getAsString();
    64                 String age = object.get("age").getAsString();
    65                 
    66                 //获取节点存储的json对象
    67                 JsonObject asJsonObject = object.getAsJsonObject("msg");
    68                 JsonElement jsonElement2 = asJsonObject.get("a");//获取对象中的a节点
    69                 String a = jsonElement2.getAsString();//获取a节点的值
    70                 
    71                 //获取对象中的b节点
    72                 JsonElement jsonElement3 = asJsonObject.get("b");
    73                 String b = jsonElement3.getAsString();//获取b节点的值
    74                 
    75                 Gson gson = new Gson();
    76                 //获取节点存储的json对象
    77                 JsonArray jsonArray = object.getAsJsonArray("core");
    78                 //遍历JsonArray对象
    79                 Iterator it = jsonArray.iterator();
    80                 while(it.hasNext()){
    81                     JsonElement e = (JsonElement)it.next();
    82                     //JsonElement转换为JavaBean对象
    83                     Student jbDemo = gson.fromJson(e, Student.class);
    84                     System.out.println(jbDemo.getName() + "-" + jbDemo.getAge());  //zhangsan-25  lisi-26
    85                 }
    86         } catch (JsonIOException e) {
    87             e.printStackTrace();
    88         } catch (JsonSyntaxException e) {
    89             e.printStackTrace();
    90         } catch (FileNotFoundException e) {
    91             e.printStackTrace();
    92         }
    93     }
    94 }
     1 import com.google.gson.Gson;
     2 
     3 public class JsonAnalysis2 {
     4     public static void main(String[] args) {
     5         /**
     6          * gson提供的方法:
     7          *         fromJson(String json, Class<T> classOfT) 
     8          *         fromJson(JsonElement json, Class<T> classOfT) 
     9          *     解析json字符串或者JsonElement成指定的对象
    10          */
    11         String jsonData = "{'name':'John', 'age':20}";
    12         Gson gson = new Gson();
    13         Student stu = gson.fromJson(jsonData,Student.class);
    14         System.out.println(stu.getName() + "-" + stu.getAge());
    15     }
    16 }
     1 import com.google.gson.Gson;
     2 
     3 public class JsonAnalysis3 {
     4     public static void main(String[] args) {
     5         Gson gson = new Gson();
     6         //解析基本类型数据
     7         int i = gson.fromJson("1", int.class);  
     8         double d = gson.fromJson(""1.11"", double.class); 
     9         double d2 = gson.fromJson("1.11", double.class);
    10         boolean b = gson.fromJson("true", boolean.class); 
    11         String s = gson.fromJson("str", String.class);
    12         
    13         System.out.println(i);    // 1
    14         System.out.println(d);    // 1.11 
    15         System.out.println(d2);    // 1.11  
    16         System.out.println(b);    // true 
    17         System.out.println(s);    // str
    18     }
    19 }
     1 import com.google.gson.Gson;
     2 
     3 public class JsonAnalysis4 {
     4     public static void main(String[] args) {
     5         Gson gson = new Gson();
     6         /**
     7          * toJson(Object src) 返回一个字符串。    对象转成json字符串
     8          */
     9         Gson gson1 = new Gson();  
    10         String s1= gson1.toJson(1);  
    11         String s2= gson1.toJson(false); 
    12         String s3= gson1.toJson("str"); 
    13         
    14         System.out.println(s1);// 1
    15         System.out.println(s2);// false 
    16         System.out.println(s3);//"str" 
    17     }
    18 }
     1 import com.google.gson.Gson;
     2 
     3 public class JsonAnalysis5 {
     4     public static void main(String[] args) {
     5         Gson gson = new Gson();
     6         /**
     7          * 字符串数组转成json字符串,然后将json字符串转成字符串数组
     8          */
     9         String jsonss = "[aa,bb,cc]";
    10         //将json字符串转成对应的字符串类型的数组
    11         String[] str = gson.fromJson(jsonss, String[].class);  
    12         for (String st:str) {  
    13              System.out.println(st);//遍历得到数组中的元素
    14         }  
    15     }
    16 }
     1 import java.util.ArrayList;
     2 import java.util.List;
     3 
     4 import com.google.gson.Gson;
     5 import com.google.gson.reflect.TypeToken;
     6 /**
     7  * 解析list
     8  */
     9 public class JsonAnalysis6 {
    10     public static void main(String[] args) {
    11         Gson gson = new Gson();
    12         //自己创建json字符串
    13         List<String> list = new ArrayList<String>();
    14         list.add("a");
    15         list.add("b");
    16         String json = gson.toJson(list);//将list转成Json格式的字符串
    17         
    18         //将json字符串转成对应的字符串类型的数组
    19         List<String> strList = gson.fromJson(json, new TypeToken<List<String>>() {}.getType());  
    20         for (String st:strList) {  
    21              System.out.println(st);//遍历得到数组中的元素
    22         }  
    23     }
    24 }

    GSON2

     1 public class User {
     2     private String name;
     3     private int age;
     4 
     5     // @SerializedName("email_address") // test5()使用
     6     // @SerializedName(value="emailAddress",alternate={"email","email_address"})//test6()使用
     7     private String emailAddress;
     8     public User() {}
     9     public User(String name, int age) {
    10         this.name = name;
    11         this.age = age;
    12     }
    13     public User(String name, int age, String emailAddress) {
    14         this.name = name;
    15         this.age = age;
    16         this.emailAddress = emailAddress;
    17     }
    18     //set和get方法
    19     public String getName() {
    20         return name;
    21     }
    22     public void setName(String name) {
    23         this.name = name;
    24     }
    25     public int getAge() {
    26         return age;
    27     }
    28     public void setAge(int age) {
    29         this.age = age;
    30     }
    31     public String getEmailAddress() {
    32         return emailAddress;
    33     }
    34     public void setEmailAddress(String emailAddress) {
    35         this.emailAddress = emailAddress;
    36     }
    37 }
     1 public class Resulter<T> {
     2     public int code;
     3     public String message;
     4     public T data;
     5     public Resulter() {}
     6     //set和get方法
     7     public int getCode() {
     8         return code;
     9     }
    10 
    11     public void setCode(int code) {
    12         this.code = code;
    13     }
    14 
    15     public String getMessage() {
    16         return message;
    17     }
    18 
    19     public void setMessage(String message) {
    20         this.message = message;
    21     }
    22 
    23     public T getData() {
    24         return data;
    25     }
    26 
    27     public void setData(T data) {
    28         this.data = data;
    29     }
    30 }
      1 import java.util.ArrayList;
      2 import java.util.List;
      3 
      4 import com.google.gson.Gson;
      5 import com.google.gson.reflect.TypeToken;
      6 
      7 public class TestGson {
      8     private Gson gson = new Gson();
      9     /**
     10      * 测试main
     11      */
     12     public static void main(String[] args) {
     13         TestGson test = new TestGson();
     14         test.test9();
     15     }
     16     /**
     17      * json字符串转基本数据类型(String虽不是基本数据类型,但是是值传递,与基本数据类型处理相似)
     18      */
     19     public void test1() {
     20         int i = gson.fromJson("100", int.class); // 100
     21         double d = gson.fromJson("99.99", double.class); // 99.99
     22         boolean b = gson.fromJson("true", boolean.class); // true
     23         String str = gson.fromJson("String", String.class); // String
     24 
     25         System.out.println(i);
     26         System.out.println(d);
     27         System.out.println(b);
     28         System.out.println(str);
     29     }
     30 
     31     /**
     32      * 基本数据类型转json字符串(String虽不是基本数据类型,但是是值传递,与基本数据类型处理相似)
     33      */
     34     public void test2() {
     35         String jsonNumber = gson.toJson(100); // 100
     36         String jsonBoolean = gson.toJson(false); // false
     37         String jsonString = gson.toJson("String"); // "String"
     38 
     39         System.out.println(jsonNumber);
     40         System.out.println(jsonBoolean);
     41         System.out.println(jsonString);
     42     }
     43 
     44     /**
     45      * java对象转json字符串
     46      */
     47     public void test3() {
     48         User user = new User("ZhangSan", 24);
     49         String jsonObject = gson.toJson(user); // {"name":"ZhangSan","age":24}
     50         System.out.println(jsonObject);
     51     }
     52 
     53     /**
     54      * json字符串转java对象
     55      */
     56     public void test4() {
     57         String jsonString = "{name:ZhangSan,age:24}";
     58         User user = gson.fromJson(jsonString, User.class);
     59         System.out.println(user.getName() + " | " + user.getAge() + " | " + user.getEmailAddress());
     60     }
     61 
     62     /**
     63      * @SerializedName()的使用_1
     64      */
     65     public void test5() {
     66         User user = new User("ZhangSan", 24, "abc@163.com");
     67         String jsonObject = gson.toJson(user);
     68         // User.emailAddress未加'@SerializedName("email_address")'时的转换效果如下:
     69         // {"name":"ZhangSan","age":24,"emailAddress":"abc@163.com"}
     70 
     71         // User.emailAddress加了'@SerializedName("email_address")'时的转换效果如下:
     72         // {"name":"ZhangSan","age":24,"email_address":"abc@163.com"}
     73         System.out.println(jsonObject);
     74     }
     75 
     76     /**
     77      * @SerializedName()的使用_2
     78      */
     79     public void test6() {
     80         String json = "{name:ZhangSan,age:24,emailAddress:abc_1@example.com,"
     81                 + "email:abc_2@example.com,email_address:abc_3@example.com}";
     82         User user = gson.fromJson(json, User.class);
     83 
     84         System.out.println(user.getEmailAddress()); // abc_3@example.com
     85 
     86         // 当上面的三个属性(email_address、email、emailAddress)都中出现任意一个时均可以得到正确的结果。
     87         // 注:当多种情况同时出时,以最后一个出现的值为准。
     88         // 注:alternate需要2.4版本,本次测试的版本不可使用
     89     }
     90 
     91     /**
     92      * json字符串转基本类型数组(String虽不是基本数据类型,但是是值传递,与基本数据类型处理相似)
     93      */
     94     public void test7() {
     95         String jsonArray = "[Android,Java,PHP]";
     96         String[] strings = gson.fromJson(jsonArray, String[].class);
     97         System.out.println(strings[1]);
     98     }
     99 
    100     /**
    101      * TypeToken来实现对泛型的支持_1 将String[].class 直接改为 List<String>.class 是行不通的。需要进行泛型擦除。
    102      */
    103     public void test8() {
    104         String jsonArray = "[Android,Java,PHP]";
    105         List<String> stringList = gson.fromJson(jsonArray, (new TypeToken<List<String>>() {
    106         }).getType());
    107         System.out.println(stringList.get(1));
    108     }
    109 
    110     /**
    111      * TypeToken来实现对泛型的支持_2
    112      */
    113     public void test9() {
    114         Resulter<List<User>> result = new Resulter<List<User>>();
    115         result.setCode(200);
    116         result.setMessage("success");
    117         result.setData(new ArrayList<User>() {
    118             {
    119                 for (int i = 0; i < 2; i++) {
    120                     this.add(new User("ZhangSan" + i, 25 + i, "abc@163.com"));
    121                 }
    122             }
    123         });
    124 
    125         // 不使用TypeToken无法将User的内容转换出来
    126         // fromJson()方法也是一样需要使用TypeToken指定要转换成的java对象类型
    127         String gsonStr = gson.toJson(result, (new TypeToken<Resulter<List<User>>>() {
    128         }).getType());
    129         System.out.println(gsonStr);
    130     }
    131 }


     1 import java.util.ArrayList;
     2 import java.util.List;
     3 import java.util.Map;
     4 
     5 import com.google.gson.Gson;
     6 import com.google.gson.JsonArray;
     7 import com.google.gson.JsonElement;
     8 import com.google.gson.JsonParser;
     9 import com.google.gson.reflect.TypeToken;
    10 
    11 /**
    12  * @ClassName: GsonUtil
    13  * @Description: Gson解析json工具类
    14  */
    15 public class GsonUtil {
    16     private static Gson gson = null;
    17     
    18     static {
    19         if (gson == null) {
    20             gson = new Gson();
    21         }
    22     }
    23 
    24     private GsonUtil() {}
    25 
    26     /**
    27      * 将object对象 转成json字符串
    28      */
    29     public static String GsonString(Object object) {
    30         String gsonString = null;
    31         if (gson != null) {
    32             gsonString = gson.toJson(object);
    33         }
    34         return gsonString;
    35     }
    36 
    37     /**
    38      * 将json字符串 转成泛型bean
    39      */
    40     public static <T> T GsonToBean(String gsonString, Class<T> cls) {
    41         T t = null;
    42         if (gson != null) {
    43             t = gson.fromJson(gsonString, cls);
    44         }
    45         return t;
    46     }
    47 
    48     /**
    49      * json字符串 转成list 泛型在编译期类型被擦除导致报错
    50      */
    51     public static <T> List<T> GsonToList(String gsonString, Class<T> cls) {
    52         List<T> list = null;
    53         if (gson != null) {
    54             list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
    55             }.getType());
    56         }
    57         return list;
    58     }
    59 
    60     /**
    61      * json字符串 转成list 解决泛型问题
    62      */
    63     public static <T> List<T> jsonToList(String json, Class<T> cls) {
    64         Gson gson = new Gson();
    65         List<T> list = new ArrayList<T>();
    66         JsonArray array = new JsonParser().parse(json).getAsJsonArray();
    67         for (final JsonElement elem : array) {
    68             list.add(gson.fromJson(elem, cls));
    69         }
    70         return list;
    71     }
    72 
    73     /**
    74      * json字符串中有map的 转成list
    75      */
    76     public static <T> List<Map<String, T>> GsonToListMaps(String gsonString) {
    77         List<Map<String, T>> list = null;
    78         if (gson != null) {
    79             list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {
    80             }.getType());
    81         }
    82         return list;
    83     }
    84 
    85     /**
    86      * json字符串 转成map的
    87      */
    88     public static <T> Map<String, T> GsonToMaps(String gsonString) {
    89         Map<String, T> map = null;
    90         if (gson != null) {
    91             map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
    92             }.getType());
    93         }
    94         return map;
    95     }
    96 }
  • 相关阅读:
    Spark随机深林扩展—OOB错误评估和变量权重
    Spark随机森林实现学习
    RDD分区2GB限制
    Spark使用总结与分享
    Spark核心—RDD初探
    机器学习技法--学习笔记04--Soft SVM
    机器学习技法--学习笔记03--Kernel技巧
    机器学习基石--学习笔记02--Hard Dual SVM
    机器学习基石--学习笔记01--linear hard SVM
    特征工程(Feature Enginnering)学习记要
  • 原文地址:https://www.cnblogs.com/wang1001/p/9759714.html
Copyright © 2011-2022 走看看