码迷,mamicode.com
首页 > 移动开发 > 详细

Android_Json_FastJson数据解析

时间:2015-06-17 21:51:18      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:


1.FastJson主要类

JSON

主要类,一般使用静态方法,序列化java bean序列化为json文本或者json字符串反序列化为相应对象

JSONObject

Json对象

JSONReader

JsonReader,可以在本地读取或者网络读取数据并可以反序列化

JSONWriter

JsonWriter,可以将对象序列化Json字符串,写入本地或者发送至服务

TypeReference

***重要, 类型引用在反序列化化很常用

2.常见应用  java代码
  1. public class JsonTest {

  2.   public static void main(String[] args) throws IOException, Exception {
  3.   /*
  4.   * 1.将指定的 JavaBean对象解析成Json字符串
  5.   */
  6.   Person p1 = new Person("zhangsan", 22, 1332117);
  7.   System.out.println(JSON.toJSONString(p1)); // 字段的get属性
  8.   /*
  9.   * 2.将封装了javaBean对象的集合解析成json字符串,并对该数据进行过滤
  10.   */
  11.   ValueFilter valueFilter = new ValueFilter() {
  12.   @Override
  13.   public Object process(Object source, String name, Object value) {
  14.   if (value.equals("lisi")) {
  15.   return "**敏感词汇**";
  16.   }
  17.   return value;
  18.   }
  19.   };
  20.   List list = new ArrayList();
  21.   list.add(new Person("lisi", 19, 159785));
  22.   list.add(new Person("wangwu", 10, 113123213));
  23.   list.add(new Person("zhaoliu", 29, 1444785));
  24.   System.out.println(JSON.toJSONString(list, valueFilter));
  25.   /*
  26.   * 3.将List>集合 转换为json字符串
  27.   */
  28.   List> list2 = new ArrayList>();
  29.   Map map1 = new HashMap();
  30.   map1.put("001", new Person("wangwu", 19, 159785));
  31.   map1.put("002", new Person("lisi", 19, 159785));
  32.   map1.put("003", new Person("lisi", 19, 159785));
  33.   Map map2 = new HashMap();
  34.   map2.put("001", new Person("zhaoliu", 19, 159785));
  35.   map2.put("002", new Person("lisi", 19, 159785));
  36.   map2.put("003", new Person("lisi", 19, 159785));
  37.   list2.add(map1);
  38.   list2.add(map2);
  39.   System.out.println(JSON.toJSONString(list2));
  40.   /*
  41.   * 4.将指定的字符串解析成 指定的javaBean对象(使用泛型)
  42.   */
  43.   Person p2 = JSON.parseObject(Person.getUtil(1), Person.class); // 
  44. 字段的set属性
  45.   /*
  46.   * 5.将指定的字符串解析成 封装了指定javaBean对象的集合
  47.   */
  48.   // 方法一:
  49.   List list1 = JSON.parseArray(Person.getUtil(2), Person.class);
  50.   // 方法二:
  51.   List list4 = JSON.parseObject(Person.getUtil(2), new 
  52. TypeReference>(){});
  53.   /*
  54.   * 6.将json字符串 解析成 List>集合 ,注意Type类型的定义
  55.   */
  56.   // 关键type类型
  57.   List> list3 = JSON.parseObject(Person.getUtil(3),new 
  58. TypeReference>>(){});
  59.   /*
  60.   * 7.将json字符串解析为 JsonObject对象, 由于该对象继承了map,可以得到键值对
  61.   */
  62.   JSONObject object = (JSONObject) JSON.parse(Person.getUtil(1));
  63.   System.out.println("name:" + object.getString("name"));
  64.   System.out.println("age:" + object.getIntValue("age"));
  65.   System.out.println("number:" + object.getIntValue("number"));
  66.   /*
  67.   * 8.name过滤器,只能对name进行更新,不管是否显示
  68.   */
  69.   NameFilter filter = new NameFilter() {
  70.   @Override
  71.   public String process(Object source, String name, Object value) {
  72.   // source是当前对象, name是key, value实在值
  73.   if ("age".equals(name)) {
  74.   return "AGE";
  75.   }
  76.   return name;
  77.   // {"age":22,"name":"zhangsan","number":1332117} //过滤前
  78.   // {"AGE":22,"name":"zhangsan","number":1332117} //过滤后
  79.   }
  80.   };
  81.   JSONSerializer jsonSerializer = new JSONSerializer();
  82.   jsonSerializer.getNameFilters().add(filter); // 通过增加一个过滤器,为name和值进行过滤
  83.   jsonSerializer.write(p1);
  84.   System.out.println(jsonSerializer.toString());
  85.   /*
  86.   * 9.属性过滤器PropertyFilter,满足要求的可以不做显示
  87.   */
  88.   PropertyFilter propertyFilter = new PropertyFilter() {
  89.   @Override
  90.   public boolean apply(Object source, String name, Object value) {
  91.   if ("age".equals(name)) {
  92.   return true;
  93.   }
  94.   return false;
  95.   }
  96.   };
  97.   JSONSerializer jsonSerializer2 = new JSONSerializer();
  98.   jsonSerializer2.getPropertyFilters().add(propertyFilter);
  99.   jsonSerializer2.write(list);
  100.   System.out.println(jsonSerializer2.toString());
  101.   /*
  102.   * 10.值过滤器ValueFilter,对满足要求的可以不做显示
  103.   */
  104.   ValueFilter valueFilter2 = new ValueFilter() {
  105.   @Override
  106.   public Object process(Object source, String name, Object value) {
  107.   if (value.equals(10)) {
  108.   return null;
  109.   }
  110.   return value;
  111.   }
  112.   };
  113.   JSONSerializer jsonSerializer3 = new JSONSerializer();
  114.   jsonSerializer3.getValueFilters().add(valueFilter2);
  115.   jsonSerializer3.write(list);
  116.   System.out.println(jsonSerializer3.toString());
  117.   /*
  118.   * 11.在本地路径下读取文件的json字符串信息,得到数据并赋值javaBean对象
  119.   */
  120.   JSONReader reader = new JSONReader(new FileReader("c:\\1.txt"));
  121.   // 注意type的使用
  122.   List list10 = reader.readObject(new 
  123. TypeReference>() {}.getType());
  124.   reader.close();
  125.   /*
  126.   * 12.将Object对象保存至本地路径中,保存为json字符串
  127.   */
  128.   JSONWriter writer = new JSONWriter(new FileWriter("c:\\2.txt"));
  129.   writer.writeObject(list10);
  130.   writer.close();
  131.   /*
  132.   * 13.在网络上获取json数据,并保存为对应的javaBean对象信息
  133.   */
  134.   List list11 = null;
  135.   URL url = new URL("http://192.168.117.114:8080/Test/My");
  136.   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  137.   conn.setRequestMethod("GET");
  138.   conn.setConnectTimeout(3000);
  139.   if (conn.getResponseCode() == 200) {
  140.   InputStream in = conn.getInputStream();
  141.   // 通过JsonReader类得到发出的输出流对象
  142.   JSONReader reader2 = new JSONReader(new InputStreamReader(in));
  143.   // 得到Object对象
  144.   list11 = reader2.readObject(new 
  145. TypeReference>(){}.getType());
  146.   }
  147.   for (Person p : list11) {
  148.   System.out.println(p);
  149.   }
  150.   /*
  151.   * 14.将客户端的javaBean对象,上传至服务器
  152.   */
  153.   byte[] bytes = JSON.toJSONBytes(list11);
  154.   URL url2 = new URL("http://192.168.117.114:8080/Test/My");
  155.   HttpURLConnection conn2 = (HttpURLConnection) url2.openConnection();
  156.   conn2.setRequestMethod("POST");
  157.   conn2.setConnectTimeout(3000);
  158.   conn2.setRequestProperty("content-length", 
  159. String.valueOf(bytes.length));
  160.   conn2.setRequestProperty("content-type","application/x-www-form-urlencoded");
  161.   conn2.setDoOutput(true);
  162.   OutputStream os = conn2.getOutputStream();
  163.   os.write(bytes, 0, bytes.length);
  164.   os.close();
  165.   if (conn2.getResponseCode() == 200) {
  166.   System.out.println("上传成功! ");
  167.   }
  168.   }
  169.   //////////////////////22222222
  170.   // SerialFeature 字段详细用法
  171.   }
  172.   class Person {
  173.   public static String getUtil(int type) {
  174.   switch (type) {
  175.   case 1:
  176.   return new String(
  177.   "{\"ag\te\":22,\"name\":\"zhangsan\",\"number\":1332117}");
  178.   case 2:
  179.   return new String(
  180.   "[{\"age\":19,\"name\":\"lisi\",\"number\":159785},"
  181.   + "{\"age\":10,\"name\":\"wangwu\",\"number\":113123213},"
  182.   + "{\"age\":29,\"name\":\"zhaoliu\",\"number\":1444785}]");
  183.   case 3:
  184.   return new String(
  185.   "[{\"001\":{\"age\":19,\"name\":\"lisi\",\"number\":159785},"
  186.   + "\"002\":{\"age\":19,\"name\":\"wangwu\",\"number\":159785},"
  187.   + "\"003\":{\"age\":19,\"name\":\"lisi\",\"number\":159785}},"
  188.   + "{\"001\":{\"age\":23,\"name\":\"lisi\",\"number\":159785},"
  189.   + "\"002\":{\"age\":19,\"name\":\"lisi\",\"number\":159785},"
  190.   + "\"003\":{\"age\":19,\"name\":\"lisi\",\"number\":159785}}]");
  191.   }
  192.   return null;
  193.   }
  194.   private String name;
  195.   private int age;
  196.   private int number;
  197.   public Person() {
  198.   super();
  199.   }
  200.   public Person(String name, int age, int number) {
  201.   super();
  202.   this.name = name;
  203.   this.age = age;
  204.   this.number = number;
  205.   }
  206.   public String getName() {
  207.   return name;
  208.   }
  209.   public void setName(String name) {
  210.   this.name = name;
  211.   }
  212.   public int getAge() {
  213.   return age;
  214.   }
  215.   public void setAge(int age) {
  216.   this.age = age;
  217.   }
  218.   public int getNumber() {
  219.   return number;
  220.   }
  221.   public void setNumber(int number) {
  222.   this.number = number;
  223.   }
  224.   @Override
  225.   public String toString() {
  226.   return "Person [age=" + age + ", name=" + name + ", number=" + number + 
  227. "]";
  228.   }
  229.   }
复制代码
  3.SerialFeature的说明
  (1).SerialFeature类的定义
  java代码
  1. // 在枚举中SerializerFeature有如下部分定义

  2.   public enum SerializerFeature {
  3.   QuoteFieldNames,
  4.   UseSingleQuotes,
  5.   WriteMapNullValue,
  6.   WriteEnumUsingToString,
  7.   UseISO8601DateFormat,
  8.   SkipTransientField
  9.   }
复制代码
  (2).SerialFeature类的使用
  java代码
  1. Date date = new Date(1308841916550L);

  2.   // 缺省输出 System.out.println(JSON.toJSONString(date)); // 1308841916550
  3.   // 使用特性 UseISO8601DateFormat
  4.   System.out.println(JSON.toJSONString(date, 
  5. SerializerFeature.UseISO8601DateFormat));// "2011-06-23T23:11:56.550"
  6.   // 组合两个Feature(UseISO8601DateFormat和UseSingleQuotes)输出日期
  7.   SerializerFeature[] features = {SerializerFeature.UseISO8601DateFormat, 
  8. SerializerFeature.UseSingleQuotes };
  9.   System.out.println(JSON.toJSONString(date, features)); // 
  10. ‘2011-06-23T23:11:56.550‘
复制代码



(3).详细说明

Featurs枚举值

缺省值

说明

QuoteFieldNames

true

序列化输出含引号的字段

UseSingleQuotes

false

使用单引号而不是双引号序列化

WriteMapNullValue

false

空值是否输出。大多数情况,值为null的属性输出是没有意义的,缺省这个特性是打开的。
{‘id‘:123,birthday : null}    <---区别--->         {"id":123}

WriteEnumUsingToString

false

Enum输出为枚举值还是枚举下标

UseISO8601DateFormat

false

Date使用ISO8601格式输出日期

SkipTransientField

true

如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略

WriteNullListAsEmpty

false

list字段如果为null,输出为[],而不是null

WriteNullNumberAsZero

false

数值字段如果为null,输出为0,而不是null

WriteNullBooleanAsFalse

false

Boolean字段如果为null,输出为false,而不是null

WriteNullStringAsEmpty

false

字符类型字段如果为null,输出为"",而不是null

SortField

false

按字段名称排序后输出

WriteTabAsSpecial

false


Android_Json_FastJson数据解析

标签:

原文地址:http://blog.csdn.net/leaning_wk/article/details/46535147

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!