How to fluently build JSON in Java?

后端 未结 9 1031
别跟我提以往
别跟我提以往 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:32

    You can use one of Java template engines. I love this method because you are separating your logic from the view.

    Java 8+:

    
      com.github.spullara.mustache.java
      compiler
      0.9.6
    
    

    Java 6/7:

    
      com.github.spullara.mustache.java
      compiler
      0.8.18
    
    

    Example template file:

    {{#items}}
    Name: {{name}}
    Price: {{price}}
      {{#features}}
      Feature: {{description}}
      {{/features}}
    {{/items}}
    

    Might be powered by some backing code:

    public class Context {
      List items() {
        return Arrays.asList(
          new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
          new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
        );
      }
    
      static class Item {
        Item(String name, String price, List features) {
          this.name = name;
          this.price = price;
          this.features = features;
        }
        String name, price;
        List features;
      }
    
      static class Feature {
        Feature(String description) {
           this.description = description;
        }
        String description;
      }
    }
    

    And would result in:

    Name: Item 1
    Price: $19.99
      Feature: New!
      Feature: Awesome!
    Name: Item 2
    Price: $29.99
      Feature: Old.
      Feature: Ugly.
    
    • mustache: https://github.com/spullara/mustache.java
    • But there is also Jinja: https://github.com/HubSpot/jinjava
    • And carrot: https://github.com/codeka/carrot

提交回复
热议问题