2

我正在尝试使用 XStream 将一个小对象图输出到 JSON。仅输出,无需反序列化。

对象非常简单:

@XStreamAlias("players")
public class Players {

    @XStreamImplicit
    private List<Player> players = new ArrayList<Player>();

    public Players() {
        for (int i = 0; i < 5; ++i) {
            players.add(new Player("Player " + i));
        }
    }
}

@XStreamAlias("player")
public class Player {
    private String name;
    public Player(String name) {
        this.name = name;
    }
}

幸运的是,JSON 中省略了不必要的列表包装元素:

{ players: { player: { name: "Player 4"}}}

但不幸的是,只打印了最后一个元素

我正在使用 XStream 1.4.2,初始化如下:

XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.aliasSystemAttribute(null, "class");
xstream.autodetectAnnotations(true);
String out = xstream.toXML(xstramAliasObject);

据我所见,设置类似于这个问题:XStream Alias of List root elements

我的例子有什么问题?

提前致谢!问候,迈克尔

4

1 回答 1

0

我正在使用相同的库,但收到整个消息..

{"players": {
  "player": {
    "name": "Player 0"
  },
  "player": {
    "name": "Player 1"
  },
  "player": {
    "name": "Player 2"
  },
  "player": {
    "name": "Player 3"
  },
  "player": {
    "name": "Player 4"
  }
}}

这是代码..

public static void main(String[] args) {
        Players xstramAliasObject = new Players();
        XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.aliasSystemAttribute(null, "class");
        xstream.autodetectAnnotations(true);
        System.out.println("--- "+xstream.toXML(xstramAliasObject));
    }
于 2015-07-29T13:32:43.893 回答