简体   繁体   English

如何使用gson将对象序列化为一个元素的列表

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

I have some json string like this:我有一些这样的 json 字符串:

example1例子1

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

example2例子2

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

and I want to serialize with one JAVA object like this:我想用这样的一个JAVA 对象进行序列化:

@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但它会抛出异常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?或者有什么方法可以用一个对象序列化两种不同类型的 json 字符串?

I don't think it is a good way to serialize two different types of json strings with ONE object.我认为用ONE对象序列化两种不同类型的 json 字符串不是一种好方法。

For example 1, the Object should be like this:例如1,对象应该是这样的:

@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:而例如2,对象应该是这样的:

@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:在 JSON 中:

  • Objects are enclosed directly in curly brackets {} While JSON对象直接用大括号括起来 {} 而 JSON
  • Arrays that are enclosed in square brackets [] inside JSON Objects.在 JSON 对象中用方括号 [] 括起来的数组。

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.请参考 Gson 的文档。

I solved it by modify JsonObject.我通过修改 JsonObject 解决了它。 I use this code to convent JsonObject to JsonArray, so I can deserializer it like JsonArray.我使用此代码将 JsonObject 转换为 JsonArray,因此我可以像 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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