Search code examples
javajsonflexjson

how to convert json to java Obj using flexjson?


Yes. It is my code what convert java obj to JSON using flexjson. It is ok by the test. But I don't know how to convert JSON to java Obj. Anybody knows? Thanks for your help in advance.

        /**
         * convert java obj to json using flexjson 2.1.
         * 
         * @param obj
         * @return jsonStr
         */
    public static String bean2Json(Object obj) {
        JSONSerializer serilizer = new JSONSerializer();
        return serilizer.serialize(obj);
    }

     /**
      * convert json to java obj using flexjson 2.1.
      * 
      * @param jsonStr
      * @param objClass
      *
      * @return obj
      */
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
      // TODO
    }

Solution

  • import flexjson.JSONDeserializer;
    import flexjson.JSONSerializer;
    
    public class DeserializerTest {
        public static void main(String[] args)
        {
            JSONSerializer serilizer = new JSONSerializer();
            Apple oneApple = new Apple(123);
            String appleString = serilizer.serialize(oneApple);
    
            // Convert Apple String to Apple object here
            Apple deserializedApple = new JSONDeserializer<Apple>().deserialize( appleString );
            System.out.println("AppleID: "+deserializedApple.appleID);
        }
    }
    

    public class Apple {
        public int appleID;
    
        public Apple(){}
    
        public Apple(int pAppleID){
            this.appleID=pAppleID;
        }
    }
    

    The expected output should be AppleID: 123

    Hope it helps