How to fluently build JSON in Java?

后端 未结 9 1057
别跟我提以往
别跟我提以往 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条回答
  •  旧时难觅i
    2020-12-07 14:29

    it's much easier than you think to write your own, just use an interface for JsonElementInterface with a method string toJson(), and an abstract class AbstractJsonElement implementing that interface,

    then all you have to do is have a class for JSONProperty that implements the interface, and JSONValue(any token), JSONArray ([...]), and JSONObject ({...}) that extend the abstract class

    JSONObject has a list of JSONProperty's
    JSONArray has a list of AbstractJsonElement's

    your add function in each should take a vararg list of that type, and return this

    now if you don't like something you can just tweak it

    the benifit of the inteface and the abstract class is that JSONArray can't accept properties, but JSONProperty can accept objects or arrays

提交回复
热议问题