How to serialize a JsonObject without too much quo

2020-07-25 12:43发布

问题:

I'm writing a small fluent wrapper over com.google.gson.JsonObject.

When I serialize my Json, I get:

{"key1":"value1","key2":"value2","key3":"{\"innerKey\":\"value3\"}"}

How do I get rid of the redundant quotes?

My code:

public class JsonBuilder {
    private final JsonObject json = new JsonObject();
    private final Map<String, JsonBuilder> children = newHashMap();

    public String toJson() {
        for (Map.Entry<String, JsonBuilder> entry : children.entrySet()) {
            String value = entry.getValue().toJson();
            add(entry.getKey(), value);
        }
        children.clear();

        return json.toString();
    }

    public JsonBuilder add(String key, String value) {
        json.addProperty(key, value);
        return this;
    }

    public JsonBuilder add(String key, JsonBuilder value) {
        Preconditions.checkArgument(!children.containsKey(key));
        children.put(key, value);
        return this;
    }
}

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

回答1:

The problem here is that you've mixed String's and Object's in your JsonBuilder class. Rather stick as closely as possible to JsonObject, and only extend it ever so slightly. If you want to wrap a JsonBuilder, do it like this, with the smallest possible modification to JsonObject:

package com.craigmj.gson;

import java.util.HashMap;

import com.google.gson.JsonObject;

class JsonBuilder {
    public final JsonObject json = new JsonObject();

    public String toJson() {
        return json.toString();
    }

    public JsonBuilder add(String key, String value) {
        json.addProperty(key, value);
        return this;
    }

    public JsonBuilder add(String key, JsonBuilder value) {
        json.add(key, value.json);
        return this;
    }
}

public class GsonTest {

    public static void main(String[] args) {

        System.out.println(new JsonBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .add("key3", new JsonBuilder()
            .add("innerKey", "value3"))
            .toJson());
    }

}

Note that I've made the json property public so that you can still use all the gson methods with it if you want the full gson functionality. (Of course, you should probably have a getter.) Unfortunately, one can't extends JsonObject since it is final.



回答2:

Use gson.toJsonTree() instead.



回答3:

You may take a look at this https://github.com/FasterXML/jackson-jr#writing-with-composers

Jackson jr is a compact alternative to full Jackson Databind component.



标签: java json gson