简体   繁体   English

如何使用GSON解析?

[英]How To parse this using GSON?

I've tried everything but i can't figure it out what Javabeans i need for this: 我已经尝试了所有方法,但是我无法弄清楚为此需要什么Javabeans:

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

Does anyone have a clue? 有人有线索吗?

if you are talking about the GSON library then you do something like this. 如果您正在谈论GSON库,那么您可以执行以下操作。

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

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). 然后,由于您的“ poitypes”字段本身必须是另一个JSON对象的一部分(您自己发布的代码段不是合法的JSON),因此您需要一个表示该字段的类,该类将具有一个称为“ poitypes”的字段”(类型为Wrapper (或任何您称其为“”)。

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. 现在,如果您的JSON对象实际上可以包含更多命名的图标(称为“ 3”,“ 4”等),那么您将无法做到这一点。 If those numbers are always going to be sequential, the JSON really ought to be a JSON array rather than an object. 如果这些数字始终是顺序的,那么JSON实际上应该是JSON数组而不是对象。 If they aren't, you'd need to use a custom JsonDeserializer to deserialize that object as a Map<Integer, NamedIcon> or some such. 如果不是,则需要使用自定义JsonDeserializer将对象反序列化为Map<Integer, NamedIcon>或类似的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM