如何获取List在Java中使用FlexJson Json序列化器从json字符串生成?
String episodeIds = "['abc', '123', '456']";
List<Long> list = new JSONDeserializer<ArrayList<Long>>().use(null, ArrayList.class).deserialize(episodeIds);
System.out.println(list);
此代码返回字符串,但必须返回 LONG)
String episodeIds = "['abc', '123', '456']";
List<Long> list = new JSONDeserializer<ArrayList<Long>>().use(null, ArrayList.class).deserialize(episodeIds);
System.out.println(list);
This code returns string but must return LONG)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您不需要第二行的
.use(null, ArrayList.class)
部分:问候,
i don't think that you need the
.use(null, ArrayList.class)
part of the second line:Regards,
在不了解 FlexJSON 的情况下,我无法确定,但我怀疑问题是由于 Java 类型擦除(如果您不熟悉这个概念,请谷歌更多信息 - 这只是意味着 Java 字节码关于声明的信息非常少)通用类型,就像您在这里所做的那样)。
因此,库无法知道您给出的预期类型(>,或隐含的返回类型);它看到的只是 ArrayList (因为 ArrayList.class 没有泛型类型信息);因为你给它的是带有字符串的 JSON,所以它必须假设你想要字符串列表。
那么如何解决这个问题呢?也许 FlexJson 有办法提供支持泛型的信息来解决这个问题。如果没有,您可以对 ArrayList 进行子类化,例如“public class MyList extends ArrayList”,将 MyList.class 传递给方法。现在它应该能够确定实际预期的类型。
或者,如果这不起作用,请尝试另一个 Java JSON 库(Jackson 或 GSON)。他们可以进行这种转换(我知道 Jackson 可以,我希望 GSON 也能够)。
Without knowing FlexJSON better I can't be sure, but problem I would suspect is due to Java Type Erasure (google more for that if you are not familiar with the concept -- it just means that Java byte code has very little information on declared generic types, like what you do here).
Because of this, library CAN NOT KNOW expected type you are giving (>, or implied return type); all it sees is ArrayList (since ArrayList.class has no generics type info); and since you are giving it JSON with Strings, it has to assume you want List of Strings.
So how to work around this? Maybe FlexJson has a way to give generics-enabled info to work around this. If not, you can sub-class ArrayList, something like 'public class MyList extends ArrayList', pass MyList.class to method. Now it SHOULD be able to determine actually expected type.
Or if that does not work, try another Java JSON library (Jackson or GSON). They can do this conversion (I know Jackson can, I would expect GSON to be able to as well).