Java Object to JSON

In the beginning, ObjectMapper to use Jackson's turn, each JSON object to be modeled, if that nested JSON 4th floor, you have to write four Java Class, and a list which can also put different types of objects, if someday demand a change, you have to dig treasure (mine) from a bunch of class inside.
 
Later JDK see there is such a wording:

 JsonObject value = Json.createObjectBuilder()
     .add("firstName", "John")
     .add("lastName", "Smith")
     .add("age", 25)
     .add("address", Json.createObjectBuilder()
         .add("streetAddress", "21 2nd Street")
         .add("city", "New York")
         .add("state", "NY")
         .add("postalCode", "10021"))
     .add("phoneNumber", Json.createArrayBuilder()
         .add(Json.createObjectBuilder()
             .add("type", "home")
             .add("number", "212 555-1234"))
         .add(Json.createObjectBuilder()
             .add("type", "fax")
             .add("number", "646 555-4567")))
     .build();

It looked so cool, one can see the entire structure of JSON, write pretty good. But such an approach, to use json-lib, json-lib is not recommended for use in or above Java 1.7, the reason for this .
 
So based on fastjson, he wrote one such builder, as a syntax sugar.

public class JsonObjectBuilder {
    private JSONObject obj = new JSONObject();
    public JsonObjectBuilder add(String key, Object value) {
        obj.put(key, value);
        return this;
    }
    public JSONObject build() {
        return obj;
    }
}
public class JsonArrayBuilder {
    private JSONArray array = new JSONArray();
    public JsonArrayBuilder add(Object item) {
        array.add(item);
        return this;
    }
    public JSONArray build() {
        return array;
    }
}
public class JsonBuilder {
    public static JsonObjectBuilder newObject() {
        return new JsonObjectBuilder();
    }
    public static JsonArrayBuilder newArray() {
        return new JsonArrayBuilder();
    }
}

Use Demonstration:

JSONObject obj = JsonBuilder.newObject()
        .add("name", "Andy")
        .add("age", 28)
        .add("friends", JsonBuilder.newArray()
                .add(JsonBuilder.newObject()
                        .add("name", "Maggie")
                        .add("hobby", "hike")
                        .build())
                .add(JsonBuilder.newObject()
                        .add("name", "Tonny")
                        .add("city", "hongkong")
                        .build())
                .build())
        .build();

To do is to do it, but I eventually want is not something that I most want is similar to JavaScript effects.

{
    "name": ${name},
    "friends": [
        {
            "name": ${friend}
        }
    ]
}

The current Java still do not come out, expect improved Java syntax.

Guess you like

Origin blog.51cto.com/wikiou/2428360