1. 程式人生 > >JSON工具學習記錄--FastJSON

JSON工具學習記錄--FastJSON

最近做專案,總是與json打交道,在用了即可json工具後,個人認為fastJson最好用,很方便,API也清晰可見,所以記錄下使用方法,給需要的人提供幫助.(部分摘抄自網路)

一.API入口

Fastjson API入口類是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON類上的靜態方法直接完成。

public static final Object parse(String text); // 把JSON文字parse為JSONObject或者JSONArray 
public static final JSONObject parseObject
(String text); // 把JSON文字parse成JSONObject public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文字parse為JavaBean public static final JSONArray parseArray(String text); // 把JSON文字parse成JSONArray public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文字parse成JavaBean集合
public static final String toJSONString(Object object); // 將JavaBean序列化為JSON文字 public static final String toJSONString(Object object, boolean prettyFormat); // 將JavaBean序列化為帶格式的JSON文字 public static final Object toJSON(Object javaObject); 將JavaBean轉換為JSONObject或者JSONArray。

對於上面例項解釋下:
1. SerializeWriter:相當於StringBuffer
2. JSONArray:相當於List
3. JSONObject:相當於Map

二.使用例項

1.java物件轉json串

//程式碼構造了幾個按鈕,按鈕1,2,3,4是並列關係,5,61的子按鈕
 @Test
    public void testJson(){
        List<Button> buttons = new ArrayList<>();
        Button button1 = new Button();
        button1.setName("button1");
        button1.setType("click");
        Button button2 = new Button();
        button2.setName("button2");
        button2.setType("click");
        Button button3 = new Button();
        button3.setName("button3");
        button3.setType("click");
        Button button4 = new Button();
        button4.setName("button4");
        button4.setType("click");
        Button button5 = new Button();
        button5.setName("button5");
        button5.setType("click");
        Button button6 = new Button();
        button6.setName("button6");
        button6.setType("click");
        button1.setSub_button(new Button[]{button5, button6});//設定5,6是1的子按鈕
        buttons.add(button1);
        buttons.add(button2);
        buttons.add(button3);
        buttons.add(button4);
        String obj = JSON.toJSONString(buttons);
        System.out.println(obj);
    }

看看打印出來的串

[
  {
    "name": "button1",
    "sub_button": [
      {
        "name": "button5",
        "type": "click"
      },
      {
        "name": "button6",
        "type": "click"
      }
    ],
    "type": "click"
  },
  {
    "name": "button2",
    "type": "click"
  },
  {
    "name": "button3",
    "type": "click"
  },
  {
    "name": "button4",
    "type": "click"
  }
]

完全符合預期結果

2.json串轉java泛型

還是繼續剛才的例子,把剛才得到的串轉回去

    //泛型使用這種轉換方式
    List<Button> buttons1 = JSON.parseObject(obj, new TypeReference<List<Button>>(){});
        System.out.println(buttons1.toString());

得到結果完全正確

[namebutton1--typeclick--sub_button[Lcom.haikong.model.menu.Button;@27d5a580, namebutton2--typeclick--sub_buttonnull, 
namebutton3--typeclick--sub_buttonnull, 
namebutton4--typeclick--sub_buttonnull]

3.json轉java物件

按照官方文件給出的方法就好了

VO vo = JSON.parseObject("...", VO.class);

4.操縱一個json物件

操縱主要通過下面兩個方法
1. JSONArray:相當於List//針對多個物件時轉換
2. JSONObject:相當於Map

        JSONArray jsonArray = JSON.parseArray(obj);
        System.out.println(jsonArray.getJSONObject(1).get("name"));//獲取json陣列中第二個元素的name值

5.時間日期處理

fastjson處理日期的API很簡單,例如:

JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS")

使用ISO-8601日期格式

JSON.toJSONString(obj, SerializerFeature.UseISO8601DateFormat);

全域性修改日期格式

JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";
JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
  • 反序列化能夠自動識別如下日期格式:
  • ISO-8601日期格式
  • yyyy-MM-dd
  • yyyy-MM-dd HH:mm:ss
  • yyyy-MM-dd HH:mm:ss.SSS
  • 毫秒數字
  • 毫秒數字字串
  • .NET JSON日期格式
  • new Date(198293238)

更多使用參考官方文件即可

6.在springMVC中使用

<mvc:annotation-driven/>預設使用jackjson來解析的,按照下面替換下就可以使用fastjson了
    <!-- 啟用預設配置 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 配置Fastjson支援 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <value>WriteMapNullValue</value>
                        <value>QuoteFieldNames</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

spring4之後的整合變更了方式:

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 配置Fastjson支援 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="fastJsonConfig" ref="fastJsonConfig"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--fastjson config-->
    <bean id="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig">
        <!-- Default charset -->
        <property name="charset" value="UTF-8" />
        <!-- Default dateFormat -->
        <property name="dateFormat" value="yyyy-MM-dd" />
        <!-- SerializerFeature -->
        <property name="serializerFeatures">
            <list>
                <value>WriteNullListAsEmpty</value>
            </list>
        </property>
    </bean>