Parsing a JSON file with GSON

后端 未结 2 900
轻奢々
轻奢々 2021-01-23 14:42

I\'m having trouble reading a JSON file into a POJO. Let me give you a snippet of what my JSON file entails:

 {
    \"Speidy\": {
        \"factionId\": \"2\",
          


        
2条回答
  •  生来不讨喜
    2021-01-23 15:34

    If you do have control the format of the JSON, I suggest the overall list structure that jmort253 suggests in his answer, i.e. [{"name":"Speidy", ... },{"name":"ShadowSlayer272", ... }].

    If you have no control over the generated JSON, here's two ways to map a JSON snippet like the one in your question {"Speidy":{ ... },"ShadowSlayer272":{ ... }} with Gson:

    • Without your Container class and a little bit of TypeToken voodoo:

      // Ask Gson to deserialize the JSON snippet into a Map.
      Type type = new TypeToken>() {}.getType();
      Map nodes = gson.fromJson(json, type);
      
    • With your Container class and a custom JsonDeserializer:

      class ContainerDeserializer implements JsonDeserializer {
        public Container deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
          List nodes = new ArrayList();
          JsonObject players = json.getAsJsonObject();
          for (Entry player : players.entrySet()) {
            String playerName = player.getKey();
            JsonElement playerData = player.getValue();
            // Use Gson to deserialize all fields except
            // for the name into a Node instance ...
            Node node = context.deserialize(playerData, Node.class);
            node.name = playerName; // ... then set the name.
            nodes.add(node);
          }
          return new Container(nodes);
        }
      }
      

      This assumes a constructor like Container(List) and allows Container instances to be immutable which is usually a Good Thing.

      Register and use the custom serializer like this:

      GsonBuilder builder = new GsonBuilder();
      // Tell Gson to use the custom ContainerDeserializer whenever
      // it's asked for a Container instance.
      builder.registerTypeAdapter(Container.class, new ContainerDeserializer());
      Gson gson = builder.create();
      
      // Ask Gson to create Container instance from your JSON snippet.
      Container container = gson.fromJson(json, Container.class);
      

提交回复
热议问题