如何使用 GSON 解析它?

发布于 2024-10-11 20:24:38 字数 211 浏览 2 评论 0原文

我已经尝试了一切,但我无法弄清楚我需要什么 Javabean:

"poitypes":{
  "2":{
     "name":"Info",
     "icon":"info.png"
  },
  "1":{
     "name":"Toilets",
     "icon":"toilets.png"
  }
}

有人知道吗?

I've tried everything but i can't figure it out what Javabeans i need for this:

"poitypes":{
  "2":{
     "name":"Info",
     "icon":"info.png"
  },
  "1":{
     "name":"Toilets",
     "icon":"toilets.png"
  }
}

Does anyone have a clue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回忆追雨的时光 2024-10-18 20:24:38

你需要这样的东西:

public class NamedIcon {
  private String name;
  private String icon;

  NamedIcon() {}

  public NamedIcon(String name, String icon) {
    this.name = name;
    this.icon = icon;
  }

  // Getters, equals, hashCode, toString, whatever else
}

然后是某种包装类:

public class Wrapper {
  @SerializedName("1") private NamedIcon one;
  @SerializedName("2") private NamedIcon two;

  // ...
}

然后,由于你的“poitypes”字段本身必须是另一个 JSON 对象的一部分(你自己发布的片段不是合法的 JSON),你需要一些表示它的类,该类有一个名为“poitypes”的 Wrapper 类型(或任何您所称的名称)的字段。

现在,如果您的 JSON 对象实际上可以包含更多命名图标(称为“3”、“4”等),那么您将无法像这样执行此操作。如果这些数字始终是连续的,那么 JSON 确实应该是 JSON 数组而不是对象。如果不是,您需要使用自定义 JsonDeserializer 将该对象反序列化为 Map 或类似类型。

You'd need something like this:

public class NamedIcon {
  private String name;
  private String icon;

  NamedIcon() {}

  public NamedIcon(String name, String icon) {
    this.name = name;
    this.icon = icon;
  }

  // Getters, equals, hashCode, toString, whatever else
}

And then some kind of wrapper class:

public class Wrapper {
  @SerializedName("1") private NamedIcon one;
  @SerializedName("2") private NamedIcon two;

  // ...
}

And then, since your "poitypes" field must itself be part of another JSON object (the snippet you've posted by itself isn't legal JSON), you'd need some class representing that, which would have a field called "poitypes" of type Wrapper (or whatever you call it).

Now, if your JSON object can actually contain more named icons (called "3", "4", etc.) then you wouldn't be able to do it quite like this. If those numbers are always going to be sequential, the JSON really ought to be a JSON array rather than an object. If they aren't, you'd need to use a custom JsonDeserializer to deserialize that object as a Map<Integer, NamedIcon> or some such.

浅黛梨妆こ 2024-10-18 20:24:38

如果您正在谈论 GSON< /a> 库然后你做这样的事情。

InputStreamReader isr = new InputStreamReader ( inputstream );
Gson g = new Gson ();
MyResultObject result = g.fromJson ( isr, MyResultObject.class );

if you are talking about the GSON library then you do something like this.

InputStreamReader isr = new InputStreamReader ( inputstream );
Gson g = new Gson ();
MyResultObject result = g.fromJson ( isr, MyResultObject.class );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文