【问题标题】:How to include the name of the class when exporting a List of objects to JSON? [duplicate]将对象列表导出到 JSON 时如何包含类的名称? [复制]
【发布时间】:2015-10-07 07:18:35
【问题描述】:

我的dog 班级如下所示:

class Dog {
    int id;
    String name;
}

我将其 List 的对象转换为 JSON:

List<Dog> myDogs = (Some initialization);
Gson gson = new Gson();
String jsonString=gson.toJson(myDogs);

JSON 字符串给了我这个结果:

[[{"id":1,"name":"Bull Dog"}],[{"id":2,"name":"German Shepherd"}]]

我希望这个字符串在开头包含类名Dog,以便我可以在客户端将它重新解析为Dog 对象中的List

我试过了:

gson.toJsonTree(myDogs,Dog.class)

但没有运气。

【问题讨论】:

  • 是的。对不起
  • np,祝你好运:)
  • 每个 Dog-Object 应该包含类名还是只包含所有 Dogs 的列表?此外,您的 JSON 看起来不像您提供的课程。它是一个包含其他列表的列表!?

标签: java json list gson


【解决方案1】:

您可以按照 herehere 中的建议在 Dog 类中使用 toString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多