Library to encode/decode from json to java.util.Map?

后端 未结 6 1704
野趣味
野趣味 2020-12-05 05:44

Does anyone knows a java library that could easily encode java Maps into json objects and the other way around?

UPDATE

For reasons couldn\'

6条回答
  •  一向
    一向 (楼主)
    2020-12-05 06:11

    You can view the site from Json.org for the list of good JSON libraries in Java.

    JSon.org's own implementation JSONObject can do just that. From their JavaDoC

     /**
         * Construct a JSONObject from a Map.
         * 
         * @param map A map object that can be used to initialize the contents of
         *  the JSONObject.
         */
        public JSONObject(Map map);
    

    you can do

    JSONObject json = new JSONObject(map);
    

    To convert JSON String back to object....

    String jsonString = "{\"name\" : \"some name\", \"age\" : 10}";
    JSONObject json = new JSONObject(jsonString);
    

    and you can access values like:

    int age = json.getInt("age");
    

    Constructor JavaDoC

    Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor.

    Parameters: source A string beginning with { (left brace) and ending with } (right brace).

提交回复
热议问题