JSON Tool Learning record--fastjson

Source: Internet
Author: User

Recent projects, always working with JSON, after the use of the JSON tool, the individual think Fastjson best use, very convenient, the API is clearly visible, so record the use of methods, to help people in need. (partly excerpt from the Internet)

I. API Portal

The Fastjson API Ingress class is Com.alibaba.fastjson.JSON, and common serialization operations can be done directly on a static method on a JSON class.

 Public Static FinalObjectParse(String text);//JSON text parse to Jsonobject or Jsonarray Public Static FinalJsonobjectparseobject(String text);//parse the JSON text into Jsonobject Public Static Final<T> Tparseobject(String text, class<t> clazz);//JSON text parse to JavaBean Public Static FinalJsonarrayParsearray(String text);//Parse the JSON text into Jsonarray Public Static Final<T> list<t>Parsearray(String text, class<t> clazz);//Parse the JSON text into a JavaBean collection Public Static FinalStringtojsonstring(Object object);//Serialize JavaBean to JSON text Public Static FinalStringtojsonstring(Object object,BooleanPrettyformat);//Serialize JavaBean to formatted JSON text Public Static FinalObjectToJSON(Object javaobject); Convert JavaBean to Jsonobject or Jsonarray.

For the above example explained below:
1. Serializewriter: Equivalent to StringBuffer
2. Jsonarray: equivalent to List
3. Jsonobject: Equivalent to map

Two. Use the instance 1.java object to go to the JSON string
The code constructs several buttons, the buttons1,2,3,4is a tie-up relationship,5,6Is1Child button @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});//Set 5, 6 is the child button of 1Buttons. Add(button1);Buttons. Add(button2);Buttons. Add(Button3);Buttons. Add(Button4);String obj = JSON. toJSONString(buttons);System. out. println(obj);}

Look at the printed string.

[  {    "name":"Button1",    "Sub_button":[{"name": "Button5", "type": "click"      }, {"nam E": " Button6 ","type": " click "      }],    "type":"click"  },  {    "name":"Button2",    "type":"click"  },  {    "name":"Button3",    "type":"click"  },  {    "name":"Button4",    "type":"click"  }]

Fully match the expected results

2.json string-To-Java generics

Or continue with the example just now and turn back the string you just got.

    //泛型使用这种转换方式    List<Button> buttons1 = JSON.parseObject(obj, new TypeReference<List<Button>>(){});        System.out.println(buttons1.toString());

Get the results exactly right

[Namebutton1--Typeclick--Sub_button[lcom.Haikong.Model.Menu.button;@27d5a580, Namebutton2--Typeclick--Sub_buttonnull, Namebutton3--Typeclick--Sub_buttonnull, Namebutton4--Typeclick--Sub_buttonnull]
3.json to Java Object

Just follow the official documentation.

VO vo = JSON.parseObject("...", VO.class);
4. Manipulating a JSON object

The operation is mainly through the following two methods
1. Jsonarray: Equivalent to list//for multiple objects when converting
2. Jsonobject: Equivalent to map

        JSONArray jsonArray = JSON.parseArray(obj);        System.out.println(jsonArray.getJSONObject(1).get("name"));//获取json数组中第二个元素的name值
5. Time and date processing

The API for Fastjson processing dates is simple, for example:

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

Use ISO-8601 date format

JSON.toJSONString(obj, SerializerFeature.UseISO8601DateFormat);

Global Modification Date format

JSON.DEFFAULT"yyyy-MM-dd";JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
    • Deserialization can automatically recognize the following date formats:
    • ISO-8601 Date format
    • Yyyy-mm-dd
    • YYYY-MM-DD HH:mm:ss
    • Yyyy-mm-dd HH:mm:ss. Sss
    • Millisecond number
    • Millisecond numeric string
    • . NET JSON date format
    • New Date (198293238)

For more information, use the official documentation

6. Use in SPRINGMVC
<mvc:annotation-driven/>默认使用jackjson来解析的,按照下面替换下就可以使用fastjson了
    <!--Enable default configuration --    <mvc:annotation-driven>        <mvc:message-converters register-defaults="true">            <!--configuration Fastjson support --            <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>
7. Notes

Fastjson does not support directly to the file parsing operations, may be added later version of the functionality, so for the file, it needs to read out to save as a string, and then can be resolved, this demand is relatively large, it is recommended to use Jackjson to parse, the latter on the file operation encapsulation is very good

JSON Tool Learning record--fastjson

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.