Using FastJson, && splicing complex nested data from json json string (not dependent entity class) directly to the key-value parsed

 

1. splicing complex nested json

FastJson kit includes two main classes: JSONObject and the JSONArray, the former represents json object, which represents json array. They both can add an object of type Object, but JSONArray not put () method, only the add () method. This is defined json array of relevant, json array can only add elements, but can not add key-value pairs. The JSONObject because it is an object, can not accommodate other objects, you can not add an object, not add () method, it will only put () method to add key-value pairs. JSONObject and JSONArray seems to only choose one of two, or put JSONObject with the () method to add a key-value pairs, or use JSONArray the add () method to add an element. In fact you can do both of, JSONObect of put (String key, Object value) method parameter value is of type Object, then this type of data can also be JSONArray type. In this case, you can add json json object in the array, to easily spliced ​​nested complex data type son.

To return json following data formats, the conventional hand-stitching will be very difficult to achieve, and error-prone.

 

 1) First, from the innermost analysis begins, the innermost layer is two json objects, {item ":" Directory Management ", " URL ":" / System / MENU / Tomain " }, the corresponding entity object has json class AdminMenu, and the outer layer is an array of two objects json included.

        The MENU1 = AdminMenu new new AdminMenu (); 
        menu1.setUrl ( "/ System / MENU / Tomain" ); 
        menu1.setName ( "Catalog Management"); // by "getItem () {return name} ", i.e., it is disposed only setName can 
        
        AdminMenu Menu2 = new new AdminMenu (); 
        menu2.setUrl ( "/ System / user / Tomain" ); 
        menu2.setName ( "user management" ); 
        
        the JSONArray level2Array = new new the JSONArray ();
         // will add an entity class two json data, FastJson entity class will automatically be converted to json objects 
        level2Array.add (the MENU1); 
        level2Array.add (Menu2);

 

2) then analyzed Level2 (json data) and Level1 (key-value pairs) is a two anonymous json object attributes, add these two properties to json object.

        JSONObject menuInfoElement = new JSONObject();
        menuInfoElement.put("Level2", level2Array);
        menuInfoElement.put("Level1", "系统管理");

 

3) And then analyze the anonymous json objects menuInfoElement is only one element of the array menuInfo json, then the anonymous json objects menuInfoElement added tomenuInfo array.

        JSONArray menuInfoArray = new JSONArray();
        menuInfoArray.add(menuInfoElement);

 

4) re-analysis, menuInfo is an attribute of the content objects json

        JSONObject contentObj = new JSONObject();
        contentObj.put("menuInfo", menuInfoArray);

 

5) Finally, the 'status' 'content' 'message' as the final properties of the returned object json

        JSONObject jsonMainObj = new JSONObject();
        jsonMainObj.put("status", "success");
        jsonMainObj.put("message", "查询成功");
        jsonMainObj.put("content", contentObj);

 

Test code

  @Test
     public  void testJson1 () 
    { 
        AdminMenu the MENU1 = new new AdminMenu (); 
        menu1.setUrl ( "/ System / MENU / Tomain" ); 
        menu1.setName ( "Catalog Management"); // by "getItem () {return name } ", it can be provided only setName 
        
        AdminMenu Menu2 = new new AdminMenu (); 
        menu2.setUrl ( " / System / user / Tomain " ); 
        menu2.setName ( " user management " ); 
        
        the JSONArray level2Array = new new the JSONArray ();
         / / added a two json data entity class, FastJson entity class will automatically become the object json
        level2Array.add(menu1); 
        level2Array.add(menu2);
        
        JSONObject menuInfoElement = new JSONObject();
        menuInfoElement.put("Level2", level2Array);
        menuInfoElement.put("Level1", "系统管理");
        
        JSONArray menuInfoArray = new JSONArray();
        menuInfoArray.add(menuInfoElement);
      
        
        JSONObject contentObj = new JSONObject();
        contentObj.put("menuInfo", menuInfoArray);
        
        JSONObject jsonMainObj = new JSONObject();
        jsonMainObj.put("status", "success");
        jsonMainObj.put("message", "查询成功");
        jsonMainObj.put("content", contentObj);
        
        System.out.println(jsonMainObj.toJSONString());
    }

 

String output

{ "message": "Query successful", 
"Content": { "menuInfo": [{ "Level2": [{ "Item": "Directory Management", "name": "Directory Management", "url": " / system / MENU / Tomain "}, 
{" Item ":" user management "," name ":" user management "," URL ":" / system / user / Tomain "}], 
" Level-1 ":" system management "}]}, 
" Status ":" Success "}

 

2. Do not rely on the entity class, parses the format string from json the key-value pair

There JSONObject parseObject (String text, Class <T> clazz) static method, the character string parsed into json java objects of type T; JSONArray but also parseArray (String text, Class <T> clazz) parses the string to json List < T> collection object.

But they all need to pass a Class object as a parameter, in other words, you must have a Class corresponding entity classes, and many times we will be one of the key-value pairs parsed once, only once went to the temporary use of it create a new entity class, the class will lead to an explosion.

 Put another idea, JSONArray.parseArray (String text) will return a JSONArray object. The methods according to add (Object obj) into the parametric type Object, then it may be an element type entity class may be a common target json JSONObject ,. But currently we call parseArray (String text) static method was introduced to a json string, in order to construct a json array, you can be sure of its internal element type must be JSONObject, where each element will therefore forced from Object JSONObject converted to type, and then to remove the key from each JSONObject.

@Test
     public  void parseJsonText () 
    { 
        String MenuList = "[{ 'ID':. 1, 'Locked': to false, 'loginedTime': '2014-01-21'}," 
            + "{ 'ID': 2, ' Locked ': to true,' loginedTime ':' 2015-03-22 '},] " ;
         / * 
         * there attribute names corresponding User class, it can be written in this form, but there is no User class, 
         * can not be achieved List <the User> Ulist = JSONArray.parseArray (MenuList, User.class); 
         * / 
        the JSONArray jUsers = JSONArray.parseArray (MenuList);
         / ** 
         * this may for loop 
         * for (int i = 0; i <jUsers.size (); I ++) { 
            the JSONObject = User jUsers.getJSONObject (I);
             }
         */
        for(Object userObj: jUsers) 
        { 
            the JSONObject juser = (the JSONObject) userObj; // cast, knowing the type of the specific element is the JSONObject, then no error 
            / ** 
             * { 'ID': key-value pair. 1} 1 not quoted values, FASTJSON that it is digital, 
             * if { 'id': '1' } format, FASTJSON that it is a string, the error is converted to Integer 
             * / 
            Integer ID = (Integer) jUser.get ( "ID" );
             / * 
             * { 'Locked':} key-value pairs to false no quotes, FASTJSON treated as boolean types, 
             * if { 'locked': 'false' } format, FASTJSON regarded as a String , cast runtime error boolean 
             * 
             * / 
            boolean Locked = ( boolean ) jUser.get ( "Locked" );
            String loginTime = (String) jUser.get ( "loginedTime" ); 
            System.out.println ( "User id:" + id + "? , Locked it" + locked + "sign in Time:" + logintime); 
        } 
    }

 

 

The results output

 

     Also note, the front end of a weakly typed language is JavaScript language, which can be variable according to its type to infer specific values, while JAVA is a strongly typed language, number of strings and a clear distinction.

{ 'Id', 23} and { 'id', '23'} distal no difference, but FastJson resolve both formats are significantly different, the former key value (23) as numbers without quotes, the latter values ​​are quoted for the key ( '23') as a string.

    @Test
     public  void parseJsonError () 
    { 
        String MenuList = "[{ 'ID':. 1, 'Locked': to false, 'loginedTime': '2014-01-21'}," 
            + "{ 'ID': 2, ' Locked ': to true,' loginedTime ':' 2015-03-22 '},] " ; 
    
        the JSONArray jUsers = JSONArray.parseArray (MenuList);
         the try {
             for (Object userObj: jUsers) 
            { 
                the JSONObject juser = (the JSONObject) userObj; / / cast, knowing the type of the specific element is the JSONObject, then no error 
              
                String ID = (String) jUser.get ( "ID");// the error
              
                Locked String = (String) jUser.get ( "Locked"); // The error 
                String logintime = (String) jUser.get ( "loginedTime" ); 
                System.out.println ( "User id:" + id + ", ? lock yet "+ locked +" sign in time: "+ logintime); 
            } 
        } the catch (Exception E) { 
            e.printStackTrace (); 
        } 
    }

 

Abnormal console prompt type conversion

 

Guess you like

Origin www.cnblogs.com/gocode/p/parse-key_value-without-entity-and-concat-nested-json-by-fastjson.html