我们怎么能在json中隐含

时间:2012-12-04 13:07:32

标签: java json xstream

我们是否有任何可以替换@xstreamImplicit for JSON的注释,因为XstreamImplicit仅适用于XML?

例如:

Class A {

  @XstreamImplicit
  private List<Apple> apples;
}

XML:

<apple>
  .....
  .....
</apple>
<apple>
   ....
   ....
</apple>

JSON:

{ apples: [{...}] }

我希望以下列格式输出所需的JSON:

[{...}]

2 个答案:

答案 0 :(得分:0)

根据"Write to JSON with the self-contained JSON driver dropping the root" in the JSON tutorial,你可以这样写:

XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
    public HierarchicalStreamWriter createWriter(Writer writer) {
        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
    }
});

答案 1 :(得分:0)

尝试做这样的事情,

我不赞成这个方法在从此获取的字符串中重新创建对象时工作正常。

Class A {

  private List<Apple> apples;
  public static void setXstreamAlias(XStream xstream)
      xstream.alias("apples", List.class, Apple.class);
      xstream.addImplicitArray(A.class, "apples");
  }
}

在将该对象用于字符串序列化之前,应该调用此方法。

像这样,

A a = new A();
// setting some values to your apple here...
.
.
.

// finally
XStream xstream;
xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
A.setXstreamAlias(xstream);
String output = xstream.toXML(a) ;

我希望这能帮到你,

但这有一些问题, 请浏览此链接:https://stackoverflow.com/questions/13966871/xstream-json-arraylist-handling-after-xstreamimplicit-the-arraylist-variable

坚持正确如果我错了任何上述理解。谢谢。