How to fluently build JSON in Java?

后端 未结 9 1011
别跟我提以往
别跟我提以往 2020-12-07 13:43

I\'m thinking of something like:

String json = new JsonBuilder()
  .add(\"key1\", \"value1\")
  .add(\"key2\", \"value2\")
  .add(\"key3\", new JsonBuilder()         


        
9条回答
  •  既然无缘
    2020-12-07 14:20

    String json = new JsonBuilder(new GsonAdapter())
      .object("key1", "value1")
      .object("key2", "value2")
      .object("key3")
        .object("innerKey1", "value3")
        .build().toString();
    

    If you think the above solution is elegant, then please try out my JsonBuilder lib. It was created to allow one way of building json structures for many types of Json libraries. Current implementations include Gson, Jackson and MongoDB. For ie. Jackson just swap:

    String json = new JsonBuilder(new JacksonAdapter()).
    

    I'll happily add others on request, it`s also quite easy to implement one by oneself.

提交回复
热议问题