简体   繁体   中英

How to serialize an object to a list of one elements with gson

I have some json string like this:

example1

{ "path":{ "start":"abc" }, "name":"Fork1" }

example2

{ "path":[{ "start":"abc" }, { "start":"def" }], "name":"Fork1" }

and I want to serialize with one JAVA object like this:

@Data
public static class ForkNode {
    private List<Path> path;
    private String name;
}

@Data
public static class Path {
    private String start;
}
new Gson().fromJson(jsonStr, ForkNode.class)

but it will throw an exception IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 11 path $.path

So how do I treat the first example as a list of one elements? Or is there any way I can serialize two different types of json strings with one object?

I don't think it is a good way to serialize two different types of json strings with ONE object.

For example 1, the Object should be like this:

@Data
public static class ForkNode {
    // only one path 
    private Path path;
    private String name;
}

@Data
public static class Path {
    private String start;
}
new Gson().fromJson(jsonStr, ForkNode.class)

While For example 2, the Object should be like this:

@Data
public static class ForkNode {
    // several paths 
    private List<Path> path;
    private String name;
}

@Data
public static class Path {
    private String start;
}
new Gson().fromJson(jsonStr, ForkNode.class)

In JSON:

  • Objects are enclosed directly in curly brackets {} While JSON
  • Arrays that are enclosed in square brackets [] inside JSON Objects.

One more thing, If you do really want to do that, I think you need to implement a custom deserializer by yourself. Please ref the doc of Gson.

I solved it by modify JsonObject. I use this code to convent JsonObject to JsonArray, so I can deserializer it like JsonArray.

public void objectToArray(JsonObject jsonObject, String node) {
    JsonElement jsonElement = jsonObject.get(node);
    if (jsonElement instanceof JsonObject) {
        JsonArray array = new JsonArray();
        array.add(jsonElement);
        jsonObject.remove(node);
        jsonObject.add(node, array);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM