How to deserialize JSON into flat, Map-like structure?

后端 未结 7 2131
醉梦人生
醉梦人生 2020-12-01 06:34

Have in mind that the JSON structure is not known before hand i.e. it is completely arbitrary, we only know that it is JSON format.

For example,

The followin

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 07:27

    You can achieve something like that using the Typesafe Config Library as in the following example:

    import com.typesafe.config.*;
    import java.util.Map;
    public class TypesafeConfigExample {
      public static void main(String[] args) {
        Config cfg = ConfigFactory.parseString(
          "   \"Port\":\n" +
          "   {\n" +
          "       \"@alias\": \"defaultHttp\",\n" +
          "       \"Enabled\": \"true\",\n" +
          "       \"Number\": \"10092\",\n" +
          "       \"Protocol\": \"http\",\n" +
          "       \"KeepAliveTimeout\": \"20000\",\n" +
          "       \"ThreadPool\":\n" +
          "       {\n" +
          "           \"@enabled\": \"false\",\n" +
          "           \"Max\": \"150\",\n" +
          "           \"ThreadPriority\": \"5\"\n" +
          "       },\n" +
          "       \"ExtendedProperties\":\n" +
          "       {\n" +
          "           \"Property\":\n" +
          "           [                         \n" +
          "               {\n" +
          "                   \"@name\": \"connectionTimeout\",\n" +
          "                   \"$\": \"20000\"\n" +
          "               }\n" +
          "           ]\n" +
          "       }\n" +
          "   }\n" +
          "}");
    
        // each key has a similar form to what you need
        for (Map.Entry e : cfg.entrySet()) {
          System.out.println(e);
        }
      }
    }
    

提交回复
热议问题