我在想类似的东西:
String json = new JsonBuilder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", new JsonBuilder()
.add("innerKey1", "value3"))
.toJson();
哪种Java JSON库最适合这种流畅的构建?
更新:我包GSON,并得到几乎理想的结果...... 一个挂钩。
我在想类似的东西:
String json = new JsonBuilder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", new JsonBuilder()
.add("innerKey1", "value3"))
.toJson();
哪种Java JSON库最适合这种流畅的构建?
更新:我包GSON,并得到几乎理想的结果...... 一个挂钩。
Answers:
我正在使用org.json库,发现它很好并且很友好。
例:
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!"}
请参阅Java EE 7 Json规范。这是正确的方法:
String json = Json.createObjectBuilder()
.add("key1", "value1")
.add("key2", "value2")
.build()
.toString();
javax.json
Java 7及更高版本的一部分,因此应在2015年标记为正确答案。
javax.json
软件包的Maven依赖关系就是这个
我最近创建了一个库来流畅地创建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();
如果您尝试使用属性键将元素添加到数组中,或者将元素添加到不具有属性名称的对象中,则通过泛型的魔术会生成编译错误:
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发布时,您将可以执行以下操作:
Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
.add("userName", u.getName())
.add("ageInYears", u.getAge()) })
.getJson();
如果您使用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,但是您可以轻松对其进行解糖以填充Java样板。
String json = new JsonBuilder(new GsonAdapter())
.object("key1", "value1")
.object("key2", "value2")
.object("key3")
.object("innerKey1", "value3")
.build().toString();
如果您认为上述解决方案不错,请尝试使用我的JsonBuilder库。创建它是为了允许为多种类型的Json库构建json结构提供一种方法。当前的实现包括Gson,Jackson和MongoDB。对于即。杰克逊只是调换:
String json = new JsonBuilder(new JacksonAdapter()).
我会根据要求愉快地添加其他人,也很容易自己实现。
听起来您可能想了解json-lib:
http://json-lib.sourceforge.net/
Douglas Crockford是发明JSON的人。他的Java库在这里:
听起来就像json-lib的人们在Crockford离开的地方接了。两者都完全支持JSON,都使用(据我所知是兼容的)JSONObject,JSONArray和JSONFunction构造。
希望有帮助..
的参考实现包括连贯接口。查看JSONWriter及其实现toString的子类JSONStringer
比编写自己的想法要容易得多,只需将接口JsonElementInterface
与方法一起使用string toJson()
,以及AbstractJsonElement
实现该接口的抽象类,
那么您所要做的就是拥有一个JSONProperty
实现接口的类,以及JSONValue
(任何令牌),JSONArray
([...])和JSONObject
({...})来扩展抽象类
JSONObject
有名单JSONProperty
的
JSONArray
有名单AbstractJsonElement
的
您每个函数中的add函数都应采用该类型的vararg列表,然后返回 this
现在,如果您不喜欢某些东西,可以对其进行调整
接口和抽象类的好处是JSONArray
不能接受属性,但是JSONProperty
可以接受对象或数组