如何在Java中流畅地构建JSON?

如何在Java中流畅地构建JSON?,java,json,Java,Json,我在想这样的事情: String json = new JsonBuilder() .add("key1", "value1") .add("key2", "value2") .add("key3", new JsonBuilder() .add("innerKey1", "value3")) .toJson(); 哪种JavaJSON库最适合这种流畅的构建 更新:我包装了GSON并获得了几乎想要的结果 听起来您可能想要获得json库: 道格拉斯·克罗克福德是JSON

我在想这样的事情:

String json = new JsonBuilder()
  .add("key1", "value1")
  .add("key2", "value2")
  .add("key3", new JsonBuilder()
    .add("innerKey1", "value3"))
  .toJson();
哪种JavaJSON库最适合这种流畅的构建


更新:我包装了GSON并获得了几乎想要的结果

听起来您可能想要获得json库:

道格拉斯·克罗克福德是JSON的发明者;他的Java库在这里:

这听起来像是json lib的同事们从Crockford留下的地方学到的。两者都完全支持JSON,都使用(据我所知是兼容的)JSONObject、JSONArray和JSONFunction构造

“希望这能有所帮助。

我正在使用图书馆,发现它既友好又友好

例如:

String jsonString = new JSONObject()
                  .put("JSON1", "Hello World!")
                  .put("JSON2", "Hello my World!")
                  .put("JSON3", new JSONObject().put("key1", "value1"))
                  .toString();

System.out.println(jsonString);
输出:

{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}

我最近创建了一个库,用于流畅地创建Gson对象:

它的工作原理如下:

  JsonObject jsonObject = JsonBuilderFactory.buildObject() //Create a new builder for an object
  .addNull("nullKey")                            //1. Add a null to the object

  .add("stringKey", "Hello")                     //2. Add a string to the object
  .add("stringNullKey", (String) null)           //3. Add a null string to the object

  .add("numberKey", 2)                           //4. Add a number to the object
  .add("numberNullKey", (Float) null)            //5. Add a null number to the object

  .add("booleanKey", true)                       //6. Add a boolean to the object
  .add("booleanNullKey", (Boolean) null)         //7. Add a null boolean to the object

  .add("characterKey", 'c')                      //8. Add a character to the object
  .add("characterNullKey", (Character) null)     //9. Add a null character to the object

  .addObject("objKey")                           //10. Add a nested object
    .add("nestedPropertyKey", 4)                 //11. Add a nested property to the nested object
    .end()                                       //12. End nested object and return to the parent builder

  .addArray("arrayKey")                          //13. Add an array to the object
    .addObject()                                 //14. Add a nested object to the array
      .end()                                     //15. End the nested object
    .add("arrayElement")                         //16. Add a string to the array
    .end()                                       //17. End the array

    .getJson();                                  //Get the JsonObject

String json = jsonObject.toString();
Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
                                                                 .add("userName", u.getName())
                                                                 .add("ageInYears", u.getAge()) })
                                                                 .getJson();
通过泛型的魔力,如果您试图将元素添加到具有属性键的数组中,或将元素添加到没有属性名称的对象中,则会生成编译错误:

JsonObject jsonArray = JsonBuilderFactory.buildArray().addObject().end().add("foo", "bar").getJson(); //Error: tried to add a string with property key to array.
JsonObject jsonObject = JsonBuilderFactory.buildObject().addArray().end().add("foo").getJson(); //Error: tried to add a string without property key to an object.
JsonArray jsonArray = JsonBuilderFactory.buildObject().addArray("foo").getJson(); //Error: tried to assign an object to an array.
JsonObject jsonObject = JsonBuilderFactory.buildArray().addObject().getJson(); //Error: tried to assign an object to an array.
最后,API中提供了映射支持,允许您将域对象映射到JSON。目标是当Java8发布时,您将能够执行以下操作:

  JsonObject jsonObject = JsonBuilderFactory.buildObject() //Create a new builder for an object
  .addNull("nullKey")                            //1. Add a null to the object

  .add("stringKey", "Hello")                     //2. Add a string to the object
  .add("stringNullKey", (String) null)           //3. Add a null string to the object

  .add("numberKey", 2)                           //4. Add a number to the object
  .add("numberNullKey", (Float) null)            //5. Add a null number to the object

  .add("booleanKey", true)                       //6. Add a boolean to the object
  .add("booleanNullKey", (Boolean) null)         //7. Add a null boolean to the object

  .add("characterKey", 'c')                      //8. Add a character to the object
  .add("characterNullKey", (Character) null)     //9. Add a null character to the object

  .addObject("objKey")                           //10. Add a nested object
    .add("nestedPropertyKey", 4)                 //11. Add a nested property to the nested object
    .end()                                       //12. End nested object and return to the parent builder

  .addArray("arrayKey")                          //13. Add an array to the object
    .addObject()                                 //14. Add a nested object to the array
      .end()                                     //15. End the nested object
    .add("arrayElement")                         //16. Add a string to the array
    .end()                                       //17. End the array

    .getJson();                                  //Get the JsonObject

String json = jsonObject.toString();
Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
                                                                 .add("userName", u.getName())
                                                                 .add("ageInYears", u.getAge()) })
                                                                 .getJson();
集合用户=。。。;
JsonArray JsonArray=JsonBuilderFactory.buildArray(用户,{u->buildObject()
.add(“用户名”,u.getName())
.add(“ageInYears”,u.getAge())})
.getJson();
包括一个流畅的界面。签出及其toString实现子类

请参阅。 这是正确的方法:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();
如果你认为上面的解决方案很好,那么请试试我的lib。创建它是为了允许为多种类型的json库构建json结构。目前的实现包括Gson、Jackson和MongoDB。对于ie.Jackson,只需交换:

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

我很乐意根据请求添加其他工具,它也很容易自己实现。

如果您使用Jackson进行大量的
JsonNode
内置代码,您可能会对以下一组实用程序感兴趣。使用它们的好处是,它们支持更自然的链接样式,可以更好地显示正在构建的JSON的结构

下面是一个示例用法:

import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;

...

val request = object("x", "1").with("y", array(object("z", "2"))).end();
这相当于以下JSON:

{"x":"1", "y": [{"z": "2"}]}
以下是课程:

import static lombok.AccessLevel.PRIVATE;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

/**
 * Convenience {@link JsonNode} builder.
 */
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {

  /**
   * Factory methods for an {@link ObjectNode} builder.
   */

  public static ObjectNodeBuilder object() {
    return object(JsonNodeFactory.instance);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
    return object(k1, v1).with(k2, v2);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
      @NonNull String k3, String v3) {
    return object(k1, v1, k2, v2).with(k3, v3);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
    return object().with(k1, builder);
  }

  public static ObjectNodeBuilder object(JsonNodeFactory factory) {
    return new ObjectNodeBuilder(factory);
  }

  /**
   * Factory methods for an {@link ArrayNode} builder.
   */

  public static ArrayNodeBuilder array() {
    return array(JsonNodeFactory.instance);
  }

  public static ArrayNodeBuilder array(@NonNull boolean... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull int... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull String... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
    return array().with(builders);
  }

  public static ArrayNodeBuilder array(JsonNodeFactory factory) {
    return new ArrayNodeBuilder(factory);
  }

  public interface JsonNodeBuilder<T extends JsonNode> {

    /**
     * Construct and return the {@link JsonNode} instance.
     */
    T end();

  }

  @RequiredArgsConstructor
  private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {

    /**
     * The source of values.
     */
    @NonNull
    protected final JsonNodeFactory factory;

    /**
     * The value under construction.
     */
    @NonNull
    protected final T node;

    /**
     * Returns a valid JSON string, so long as {@code POJONode}s not used.
     */
    @Override
    public String toString() {
      return node.toString();
    }

  }

  public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {

    private ObjectNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.objectNode());
    }

    public ObjectNodeBuilder withNull(@NonNull String field) {
      return with(field, factory.nullNode());
    }

    public ObjectNodeBuilder with(@NonNull String field, int value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, float value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, boolean value) {
      return with(field, factory.booleanNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, String value) {
      return with(field, factory.textNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
      node.set(field, value);
      return this;
    }

    public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
      return with(field, builder.end());
    }

    public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
      return with(field, factory.pojoNode(pojo));
    }

    @Override
    public ObjectNode end() {
      return node;
    }

  }

  public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {

    private ArrayNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.arrayNode());
    }

    public ArrayNodeBuilder with(boolean value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull boolean... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(int value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull int... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(float value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(String value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull String... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNode value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull JsonNode... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
      return with(value.end());
    }

    public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
      for (val builder : builders)
        with(builder);
      return this;
    }

    @Override
    public ArrayNode end() {
      return node;
    }

  }

}
导入静态lombok.AccessLevel.PRIVATE;
导入com.fasterxml.jackson.databind.JsonNode;
导入com.fasterxml.jackson.databind.node.ArrayNode;
导入com.fasterxml.jackson.databind.node.JsonNodeFactory;
导入com.fasterxml.jackson.databind.node.ObjectNode;
导入lombok.noargsconstuctor;
导入lombok.NonNull;
导入lombok.RequiredArgsConstructor;
进口lombok.val;
/**
*便利{@link JsonNode}生成器。
*/
@NoArgsConstructor(访问=专用)
公共最终类JsonNodeBuilders{
/**
*{@link ObjectNode}生成器的工厂方法。
*/
公共静态ObjectNodeBuilder对象(){
返回对象(JsonNodeFactory.instance);
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1,布尔值v1){
使用(k1,v1)返回对象();
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1,int v1){
使用(k1,v1)返回对象();
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1,浮点v1){
使用(k1,v1)返回对象();
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1,字符串v1){
使用(k1,v1)返回对象();
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1、字符串v1、@NonNull字符串k2、字符串v2){
返回对象(k1,v1),带(k2,v2);
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1,字符串v1,@NonNull字符串k2,字符串v2,
@非空字符串k3,字符串v3){
返回对象(k1,v1,k2,v2)。带有(k3,v3);
}
公共静态ObjectNodeBuilder对象(@NonNull字符串k1,JsonNodeBuilder){
使用(k1,生成器)返回对象();
}
公共静态对象NodeBuilder对象(JsonNodeFactory工厂){
返回新的ObjectNodeBuilder(工厂);
}
/**
*{@link ArrayNode}生成器的工厂方法。
*/
公共静态ArrayNodeBuilder数组(){
返回数组(JsonNodeFactory.instance);
}
公共静态ArrayNodeBuilder数组(@NonNull boolean…value){
使用(值)返回数组();
}
公共静态ArrayNodeBuilder数组(@NonNull int…value){
使用(值)返回数组();
}
公共静态ArrayNodeBuilder数组(@NonNull字符串…值){
使用(值)返回数组();
}
公共静态ArrayNodeBuilder数组(@NonNull JsonNodeBuilder…builders){
使用(生成器)返回数组();
}
公共静态ArrayNodeBuilder数组(JsonNodeFactory工厂){
返回新的ArrayNodeBuilder(工厂);
}
公共接口JsonNodeBuilder{
/**
*构造并返回{@link JsonNode}实例。
*/
T端();
}
@所需参数构造函数
私有静态抽象类AbstractNodeBuilder实现JsonNodeBuilder{
/**
*价值的源泉。
*/
@非空
受保护的最终JSONNODEFARY工厂;
/**
*正在建设中的价值。
*/
@非空
受保护的最终T节点;
/**
*返回有效的JSON字符串,只要未使用{@code POJONode}。
*/
@凌驾
公共字符串toString(){
返回node.toString();
}
}
公共最终静态类ObjectNodeBuilder扩展了AbstractNodeBuilder{
私有对象NodeBuilder(JsonNodeFactory工厂){
super(factory,factory.objectNode());
}
带有null(@NonNull字符串字段)的公共对象NodeBuilder{
返回时带有(field,factory.nullNode());
}
具有(@NonNull字符串字段,int值)的公共ObjectNodeBuilder{
返回值为(字段,工厂编号节点(值));
}
具有(@NonNull字符串字段,浮点值)的公共ObjectNodeBuilder{
雷图
<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.8.18</version>
</dependency>
{{#items}}
Name: {{name}}
Price: {{price}}
  {{#features}}
  Feature: {{description}}
  {{/features}}
{{/items}}
public class Context {
  List<Item> 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<Feature> features) {
      this.name = name;
      this.price = price;
      this.features = features;
    }
    String name, price;
    List<Feature> features;
  }

  static class Feature {
    Feature(String description) {
       this.description = description;
    }
    String description;
  }
}
Name: Item 1
Price: $19.99
  Feature: New!
  Feature: Awesome!
Name: Item 2
Price: $29.99
  Feature: Old.
  Feature: Ugly.
String json = U.objectBuilder()
  .add("key1", "value1")
  .add("key2", "value2")
  .add("key3", U.objectBuilder()
    .add("innerKey1", "value3"))
  .toJson();
import lombok.SneakyThrows;
import org.json.JSONObject;

public class MemberJson extends JSONObject {

    @SneakyThrows
    public static MemberJson builder() {
        return new MemberJson();
    }

    @SneakyThrows
    public MemberJson name(String name) {
        put("name", name);
        return this;
    }

}
MemberJson.builder().name("Member").toString();