2012-01-16 33 views
41

Tôi đang nghĩ đến việc gì đó như:Làm thế nào để lưu loát JSON trong Java?

String json = new JsonBuilder() 
    .add("key1", "value1") 
    .add("key2", "value2") 
    .add("key3", new JsonBuilder() 
    .add("innerKey1", "value3")) 
    .toJson(); 

Những thư viện Java JSON là tốt nhất cho các loại hình tòa nhà thông thạo?

Cập nhật: Tôi gói GSON và nhận được gần như kết quả mong muốn ... with one hitch.

+0

Tôi không nghĩ rằng tôi đã thấy bất kỳ thư viện JSON nào theo phong cách đó. Có lẽ bạn có thể mở rộng một thư viện hiện có để làm những gì bạn muốn? – aroth

+0

@aroth - Tôi đang viết một trình bao bọc xung quanh com.google.gson khi chúng ta nói. – ripper234

+0

Hầu như đã sẵn sàng - http://stackoverflow.com/questions/8876271/how-to-serialize-a-jsonobject-without-too-much-quotes – ripper234

Trả lời

54

Tôi đang sử dụng thư viện org.json và thấy nó được tốt đẹp và thân thiện.

Ví dụ:

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); 

OUTPUT:

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

Điều này không thông thạo lắm. – Vlad

+0

Trang web bạn cung cấp không hoạt động nữa. Bạn có phiền khi cập nhật nó không? –

1

Có vẻ như bạn có thể muốn có được Ahold của json-lib:

http://json-lib.sourceforge.net/

Douglas Crockford là anh chàng người phát minh ra JSON; thư viện Java của ông là ở đây:

http://www.json.org/java/

Có vẻ như các folks tại json-lib nhặt nơi Crockford rời đi. Cả hai đều hỗ trợ đầy đủ JSON, cả hai đều sử dụng các cấu trúc JSONObject, JSONArray và JSONFunction.

'Hy vọng rằng sẽ giúp ..

+0

Có hỗ trợ cú pháp thông thạo không? – ripper234

+0

Có - Hãy xem tại đây: http://json-lib.sourceforge.net/snippets.html – paulsm4

9

Gần đây tôi đã tạo ra một thư viện để tạo Gson đối tượng thành thạo:

http://jglue.org/fluent-json/

Nó hoạt động như thế này:

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(); 

Và thông qua sự kỳ diệu của Generics nó tạo biên dịch lỗi nếu bạn cố gắng thêm một yếu tố để một mảng với một phím bất động sản hoặc một yếu tố để một đối tượng mà không có một tên thuộc tính:

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. 

Cuối cùng có hỗ trợ ánh xạ trong API cho phép bạn ánh xạ các đối tượng miền của mình tới JSON. Mục tiêu là khi Java8 được phát hành, bạn sẽ có thể thực hiện một việc như sau:

Collection<User> users = ...; 
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject() 
                   .add("userName", u.getName()) 
                   .add("ageInYears", u.getAge()) }) 
                   .getJson(); 
0

Việc triển khai tham chiếu trên json.org bao gồm giao diện thông thạo. Hãy xem JSONWriter và lớp con thực thi toString của mình JSONStringer

61

Xem Java Json specification. Đây là đúng cách:

String json = Json.createObjectBuilder() 
      .add("key1", "value1") 
      .add("key2", "value2") 
      .build() 
      .toString(); 
+7

Điều này sẽ được đánh dấu câu trả lời đúng vào năm 2015 vì đây là một phần của 'javax.json' trong Java 7 trở lên. –

+19

Đây là API Java EE, không phải Java SE. – igorp1024

+0

Bất kỳ ý tưởng làm thế nào để tạo ra một đối tượng JsonString từ một đối tượng String trong API javax.json? – Raymond

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

Nếu bạn nghĩ rằng giải pháp trên là thanh lịch, sau đó xin vui lòng thử JsonBuilder lib của tôi. Nó được tạo ra để cho phép một cách xây dựng các cấu trúc json cho nhiều loại thư viện Json. Các triển khai hiện tại bao gồm Gson, Jackson và MongoDB. Ví dụ:Jackson chỉ cần hoán đổi:

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

Tôi sẽ rất vui khi thêm người khác theo yêu cầu, nó cũng khá dễ thực hiện từng cái một.

2

Nếu bạn đang sử dụng Jackson thực hiện rất nhiều việc xây dựng mã, bạn có thể thấy thú vị trong bộ tiện ích sau đây. Lợi ích của việc sử dụng chúng là chúng hỗ trợ kiểu chuỗi tự nhiên hơn, cho thấy cấu trúc của JSON được xây dựng tốt hơn.

Đây là một cách sử dụng ví dụ:

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

... 

val request = object("x", "1").with("y", array(object("z", "2"))).end(); 

Đó là tương đương với JSON sau:

{"x":"1", "y": [{"z": "2"}]} 

Dưới đây là các lớp:

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; 
    } 

    } 

} 

Lưu ý rằng việc thực hiện sử dụng Lombok , nhưng bạn có thể dễ dàng desugar nó để điền vào bản mẫu Java.

0

nó dễ dàng hơn nhiều hơn bạn nghĩ để viết riêng của bạn, chỉ cần sử dụng một giao diện cho JsonElementInterface với một phương pháp string toJson(), và một lớp trừu tượng AbstractJsonElement thực hiện giao diện đó,

sau đó tất cả các bạn phải làm là có một lớp cho JSONProperty mà thực hiện giao diện, và JSONValue (bất kỳ token), JSONArray ([...]), và JSONObject ({...}) mà mở rộng các lớp trừu tượng

JSONObject có một danh sách các JSONProperty 's
JSONArray có một li st của AbstractJsonElement 's

add bạn chức năng trong mỗi nên một danh sách vararg kiểu đó, và trở this

bây giờ nếu bạn không thích một cái gì đó bạn có thể chỉ cần tinh chỉnh nó

các benifit của inteface và lớp trừu tượng là JSONArray không thể chấp nhận thuộc tính, nhưng JSONProperty có thể chấp nhận đối tượng hoặc mảng

Các vấn đề liên quan